Fetch vs. Axios.js for making http requests
If you use .fetch() there is a two-step process when handing JSON data. The first is to make the actual request and then the second is to call the .json() method on the response.
Update 06/27/17: As of May 29th, Spotify now requires authentication for all requests to their API, so the below examples will not work as written.
Here is a simple example using the Spotify API. I set the url as a variable and then pass it to fetch and set the .then() callback to console the data that gets returned from the request.
That’s great, but this is not the data you are looking for. That is the response from the server letting you know that your request went through just fine. Great, but you can’t do much with that.
To get to that data, you have to pass it to .json() first and then you can see it.
fetch(url).then(response => response.json()).then(data => console.log(data));
Now, this is the data from Spotify that we wanted.
Let’s see how this is handled with Axios.
The first step in using Axios is installing Axios. You can use npm if you want to run axios in node or a cdn if you want to run it in your browser.
npm install axios
Then, in my console, I assign the
url variable and then pass it to the
axios.get(url).then(response => console.log(response));
So by using axios you can cut out the middle step of passing the results of the http request to the .json() method. Axios just returns the data object you would expect.
The second issue that Stephen brings up is how .fetch() handles error responses. Logically you would think that if .fetch() gets an error it would enter the .catch() block and return anything there, right? Not necessarily. Here is an example.
I have altered my
url variable from the previous examples so that it is now incorrect. I would expect a 400 error at this point and for my .fetch() to go into the .catch() block but this is what happens instead.
fetch(url).catch(error => console.log('BAD', error)).then(response => console.log('GOOD', response));
I’ve added the ‘BAD’ and ‘GOOD’ strings in the responses to clarify what is happening here.
I get the 400 response code but, as you can see by the ‘GOOD’ string in the console, the .then() block was executed. How does Axios handle this? The way you would probably expect. You get any kind of error with the http request and the .catch() block is executed.
The ‘BAD’ string is there and the error is logged to the console.
The .fetch() method is a great step in the right direction of getting http requests native in ES6, but just know that if you use it there are a couple of gotchas that might be better handled by third-party libraries like Axios.