Setting the Request Method with Axios
Mastering JS
Posted on June 23, 2021
Axios is our recommended JavaScript HTTP client. While we are opposed to unnecessary outside dependencies, Axios has several advantages over fetch()
:
- Axios is isomorphic, fetch is not
- Axios throws an error when a request fails
- Automatic JSON and Form-Encoded Serialization and Parsing
- Interceptors and instances
Another reason is that Axios has neat helper methods that allow you to set the request method, like GET
or POST
. For example, below is how you can send an HTTP GET request with Axios.
const axios = require('axios');
const res = await axios.get('https://httpbin.org/get?answer=42');
res.data.args; // { answer: 42 }
Want to send a POST
request? That's easy, just change get()
for post()
and pass the request body as the 2nd parameter.
const res = await axios.post('https://httpbin.org/post', { hello: 'world' });
res.data.json; // { hello: 'world' }
Calling Axios as a Function
If you prefer the named parameters approach that fetch()
uses, you can also set the request method by setting the method
option as shown below.
let res = await axios({
method: 'GET',
url: 'https://httpbin.org/get?answer=42'
});
res.data.args; // { answer: 42 }
💖 💪 🙅 🚩
Mastering JS
Posted on June 23, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.