HTTP Requests Compared: Why Axios Is Better Than Node-Fetch (Automatic Transformations, More Secure, Can Handle Errors Better, Interceptor Support, And More Browser Friendly)

By Jeff Lewis

What Are They?

Why Do We Use Them?

What’s The Difference?

Axios GET/POST Examples

axios.get('http://pokeapi.co/api/v2/pokemon/')
.then((response) => {
return response;
})
.catch((error) => {
console.log(error);
});
}
axios.post('http://pokeapi.co/api/v2/pokemon/', {
pokemon: 'Pikachu',
})
.then((response) => {
return response;
})
.catch((error) => {
console.log(error);
});

1. Axios Performs Automatic Transformations Of JSON Data.

fetch('http://pokeapi.co/api/v2/pokemon/')
.then((response) => response.json())
.then((data) => return data)
axios.get('http://pokeapi.co/api/v2/pokemon/')
.then((response) => return response)

2. Axios Is More Secure, Featuring Built In Cross Site Forgery (XSRF) Protection

3. Axios Has Better Error Handling

fetch('http://pokeapi.co/api/v2/pokemon/')
// Missing the JSON transformation line
.then((data) => return data)
body: (...)
bodyUsed: false
headers: Headers
ok: true
status: 200
statusText: "OK"
type: "cors"
url: "http://pokeapi.co/api/v2/pokemon/"

4. Axios Has Interceptors

axios({
method: 'get',
url: 'http://pokeapi.co/api/v2/pokemon/',
data: {
pokemonNumber: '1',
}
});
// Add a request interceptor
axios.interceptors.request.use((config) => {
// Your Interceptor code to do something with the request data
// Return config
return config;
},
(error) => {
// Your Interceptor code to do something with request error
// Return error
return Promise.reject(error);
}
);
axios.interceptors.response.use((response) => {
// Your Interceptor code to do something with the response data
// Return response data
return response;
},
(error) => {
// Your Interceptor code to do something with response error
// Return error
return Promise.reject(error);
}
);

5. Axios Has The Ability To Monitor POST Request Progress

axios.post('http://pokeapi.co/api/v2/pokemon/', data, {
onUploadProgress: ({ total, loaded }) => {
// Update progress }),
})

6. Axios Has A Wider Range Of Supported Browsers

Go GET Em

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jeff Lewis

Full stack React/React Native developer, environmentalist, and beach bum.