In this case I would suggest to use the fetch API along with an abstraction layer/ wrapper function.
Fetch API is promise based, so you can use better error catching as the fetch promise fails only when there is some error with Request or Network failure.
And rest of the things are passed on to the subsequent chain of promise.
So the code will look like following:
// file: services/remote-api.js
// or some similar file name
const fetch = require('whatwg-fetch');
const request = (url, params = { method: 'GET' }) => {
if (typeof url === 'string') {
return fetch(url, params);
}
// URL is a Request object, params are not needed
return fetch(url);
}
request.then(response => {
if (response.responseCode === 200) {
// return response.json(); // in case of JSON API
return response.body();
}
// handle other 2XX
// 201 is for resource created which is a succesful request
// Add more cases for the error handling like 4XX, 5XX etc
// alert(response.responseCode);
console.warn(response);
})
request.catch(excption => {
// alert(exception.message);
console.error(exception)
});
module.exports = request;
Now just import this file and use the imported function; all error handling is in the above file. Like ex:
const api = require('services/remote-api');
const url = 'jsonplaceholder.typicode.com/posts';
// GET request
api(url).then(console.log)
// POST request
const headers = new Headers(); // attach needed ones like of CORS
const form = new FormData();
form.append('name', 'Time to Hack');
form.append('url', 'time2hack.com');
const request = new Request(url, {
method: 'POST',
headers: headers,
body: form
});
api(request).then(data => console.log);
Most pieces of examples are taken from time2hack.com/2017/11/goodbye-xmlhttprequest-ajax…