A wrapper around the new fetch API
$ npm install fetch-x
import fetchX from 'fetch-x';
GET
request
fetchX.get('/xxx?query=12345')
.then(json => console.log(json))
.catch(error => console.error(error));
POST
request
the default
Content-Type
isapplication/x-www-form-urlencoded
fetchX.post('/xxx', {
param1: 'jack',
param2: 'pony'
})
.then(json => console.log(json))
.catch(error => console.error(error));
fetchX.get(url[, data[, options]])
fetchX.post(url[, data[, options]])
fetchX.delete(url[, options])
fetchX.head(url[, options])
fetchX.put(url[, data[, options]])
fetchX.patch(url[, data[, options]])
fetchX.create([options])
const myfetch = fetchX.create({
headers: {
'Authorization': 'Bearer ' + getAPIToken(),
'X-My-Custom-Header': 'CustomHeader'
}
})
myfetch.get(url)
.then(res => res.json())
.then(json => console.log(json))
.catch(error => console.error(error))
add middleware to intercept response
fetchX.applyMiddleware({
response: [res => res.json(), json => {
if (json.code === 'xxx') {
// do something...
} else if (...) {
// do something...
} else {
// do something...
return json
}
}],
request: request => {
request.url = xxx + request.url
return request
}
})