What Is Difference Between Axios and Fetch

What is difference between Axios and Fetch?

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:

  • Fetch's body = Axios' data
  • Fetch's body has to be stringified, Axios' data contains the object
  • Fetch has no url in request object, Axios has url in request object
  • Fetch request function includes the url as parameter, Axios request function does not include the url as parameter.
  • Fetch request is ok when response object contains the ok property, Axios request is ok when status is 200 and statusText is 'OK'
  • To get the json object response: in fetch call the json() function on the response object, in Axios get data property of the response object.

Difference between Fetch and Axios

You should configure axios to use your token in one central place. For example

export const configureAxios = (token) => {
axios.interceptors.request.use(req => {
// don't give our token to non-our servers
if (isDomesticRequest(req.url)) {
req.headers.Authorization = `Bearer ${token}`;
}
return req;
});
}

Is there any reasons to use axios instead ES6 fetch

A few reasons for using Axios over Fetch:

  1. Ability to monitor request progress

This is more of a question between XMLHttpRequest (which powers axios) or Fetch API.

Fetch API currently does not provide any way to get notified of the request progress, a feature which powers feedback mechanism for large file uploads for example.

Axios, on the other hand, has this functionality built in:

axios.post('/api', data, {
onUploadProgress: ({ total, loaded }) => {
// update progress
}),
})

  1. Error handling

When your backend returns 500 Internal Server Error response code, fetch will not treat it any different from 200 OK.

This is an inconvenience in most cases since all your previous assumptions of what a response would look like are no longer valid.

Most often, when receiving an erroneous response from the server you'd want to abort the processing pipeline as soon as possible, and switch to an error handling case.

fetch(url)
.then(reponse => {
if (!(status >= 200 && status < 300)) {
return Promise.reject(new Error("Invalid response status"));
}

return response;
})
.then(response => response.json())
.then(/* normal processing */)
.catch(/* error handling */);

This is not hard to accomplish, but you'd probably want to capture this logic under some abstraction to avoid repetition, and this brings us one step closer to Web API abstraction which is Axios.

Axios does a sane thing and rejects the promise if the response returns erroneous status. This behavior is customizable as are most of the things with axios.


  1. Testing

Axios has moxios, fetch has fetch-mock.

Both of those libraries are great but in my experience, fetch-mock required additional setup to get Jest to use mocked fetch over polyfilled one.

I also like that moxios.wait() returns a promise which will be resolved after matching the request.


  1. Other features that Axios offers

For example, you can configure an interceptor which will add api key to all request parameters, or monitor active requests to show a loading screen.


Reasons for using one option over the other may vary from actual requirements to convenience.

If you need to monitor progress, use Axios (or XMLHttpRequest).

If you are writing a service worker, use Fetch.

Otherwise, use what's more convenient to you.

Proper use case for Request VS Response with Fetch/Axios

But if I am understanding correctly, that would be the request would it not?

No. The request is what calling fetch triggers the browser to send to the URL. You pass the data about what the request should look like as arguments to fetch.

You could do that indirectly (which is rarely useful) by passing a Request object as an argument to fetch

const request = new Request("http://example.com");
const response = await fetch(request);

… but fetch returns a promise that resolves as a Response.

Response should be const response = await request.json();

No. The promise returned from response.json() resolves as the result of parsing the response body as JSON.


You're confusing "the response" and "something inside the response" with "the request" and "the response"

What is difference between axios and fetch in react native?

Overall they are very similar the only difference is that axios is alittle bit more developed. Some benefits of axios:

Transformers: allow performing transforms on data before request is made or after response is received
Interceptors: allow you to alter the request or response entirely (headers as well). also perform async operations before request is made or before Promise settles
Built-in XSRF protection

for more info you can check this discussion https://github.com/axios/axios/issues/314

Axios vs Fetch in ReactJS

Axios has extensive browser support; even the old browser IE11 can run smoothly. Fetch(), on the other hand, only confirms Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+

Axios gives an easy-to-use API in a compact package for most of your HTTP connection needs. However, if you prefer to stick with native APIs, nothing stops you from achieving Axios features.

However, it's entirely possible to reproduce the Axios library's key features using the fetch() method provided by web browsers. Finally, whether it's worth loading a client HTTP API depends on whether you're comfortable working with built-in APIs.

Browser Support for fetch()

Further Reading



Related Topics



Leave a reply



Submit