API Calls Using Axios and fetch
Axios and fetch both are used to send request to APIs. The differences between them are:
- Axios: has url request object and it is a stand-alone package that can be easily installed. Axios has wide browser support.
- Fetch: has no url in request object and is build into most modern browsers. Fetch only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+
Basic Get Request
in fetch request we have to use json() method to convert data to JSON format
fetch('http://example.com')
.then(response => response.json())
.then(data => console.log(data));
in Axios data automatically converts to JSON; first we need to install axios
$ npm install axios
and then import into our component
import Axios from 'axios'
get request will look like this:
axios.get('http://example.com')
.then(function (response) {
console.log(response);
})
Basic POST request
fetch use the body property to send data, data in fetch is stringified.
fetch('http://example.com', {headers: {'Content-Type': 'application/json','Accept': 'application/json'},method: 'POST',body: JSON.stringify(data)}).then(response => response.json())
axios uses the data property
axios({
method: 'post',
url: 'http://example.com',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
check axios on github for more information
more information about fetch