DEV Community

Mastering JS
Mastering JS

Posted on

1 2

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay