Setting the Request Method with Axios

masteringjs

Mastering JS

Posted on June 23, 2021

Setting the Request Method with Axios

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 }
Enter fullscreen mode Exit fullscreen mode

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' }
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
masteringjs
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.

Related

Axios
webdev Axios

July 10, 2024

Setting the Request Method with Axios
javascript Setting the Request Method with Axios

June 23, 2021