What is difference between Axios and Fetch?

2019-01-06 12:53发布

问题:

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?

回答1:

They are HTTP request libraries...

I end up with the same doubt but the table in this post makes me go with isomorphic-fetch. Which is fetch but works with NodeJS.

http://andrewhfarmer.com/ajax-libraries/



回答2:

Fetch and Axios are very similar in functionality, but for more backward 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, this 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.

Hope this helps.



回答3:

According to mzabriskie on GitHub:

Overall they are very similar. Some benefits of axios:

  • Transformers: allow performing transforms on data before a request is made or after a response is received

  • Interceptors: allow you to alter the request or response entirely (headers as well). also, perform async operations before a request is made or before Promise settles

  • Built-in XSRF protection

I think you should use axios.



回答4:

Was curious about this too, found your question here, then found this Medium post which may prove helpful. Fetch seems a little more verbose and unforgiving: https://medium.com/@shahata/why-i-wont-be-using-fetch-api-in-my-apps-6900e6c6fe78#.wxtu3qnte



回答5:

In addition... I was playing around with various libs in my test and noticed their different handling of 4xx requests. In this case my test returns a json object with a 400 response. This is how 3 popular libs handle the response:

// request-promise-native
const body = request({ url: url, json: true })
const res = await t.throws(body);
console.log(res.error)


// node-fetch
const body = await fetch(url)
console.log(await body.json())


// Axios
const body = axios.get(url)
const res = await t.throws(body);
console.log(res.response.data)

Of interest is that request-promise-native and axios throw on 4xx response while node-fetch doesn't. Also fetch uses a promise for json parsing.



回答6:

axios and fetch are frequently used in React applications for managing network requests and managing some amount of data.

axios is a stand-alone 3rd party package that can be easily installed into a React project using NPM.

The other option you mentioned is the fetch function. This is not a package, its a singular function built into most modern browsers. With fetch you do not need to install a third party package.

So the amount of code is slightly smaller if you use fetch over axios. However, fetch is a more basic and lower level function to use to fetch data. Its not the worst thing in the world, but if you use fetch you will end up writing a lot of code that is already written for you in axios.

So its a choice between a D.I.Y. with fetch and possibly messing up if you don't know what you are doing OR just use axios and all the nuts and bolts are taken care of for you.

I personally use axios on all of my projects because axios handles network requests in a predictable fashion as opposed to some corner cases with fetch that don't make for a great experience.



回答7:

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

Advantages of axios over fetch