DEV Community

Mastering JS
Mastering JS

Posted on

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

Top comments (0)