I am calling the web service by using Fetch but the same I can do with the help of Axios. So now I am confused. Should I go for either Axios or Fetch?
Axios is best suited in terms of the transformation of data as it transforms data of JSON automatically whereas fetch requires two steps for the transformation of JSON data. If you want to transform JSON data using the Fetch API, then first you have to make a request then in response, a JSON function is called.
By using the optional timeout property in the config object, you can set the number of milliseconds before the request is terminated. One of the reasons that JavaScript developers choose Axios rather than fetch() is the ease of setting timeout.
The Axios API, as an 800 byte Fetch wrapper.
Axios is a promise based HTTP client for the browser and Node. js. Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used in plain JavaScript or with a library such as Vue or React.
Fetch and Axios are very similar in functionality, but for more backwards compatibility Axios seems to work better (fetch doesn't work in IE 11 for example, check this post)
Also, if you work with JSON requests, the following are some differences I stumbled upon with.
Fetch JSON post request
let url = 'https://someurl.com'; let options = { method: 'POST', mode: 'cors', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8' }, body: JSON.stringify({ property_one: value_one, property_two: value_two }) }; let response = await fetch(url, options); let responseOK = response && response.ok; if (responseOK) { let data = await response.json(); // do something with data }
Axios JSON post request
let url = 'https://someurl.com'; let options = { method: 'POST', url: url, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8' }, data: { property_one: value_one, property_two: value_two } }; let response = await axios(options); let responseOK = response && response.status === 200 && response.statusText === 'OK'; if (responseOK) { let data = await response.data; // do something with data }
So:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With