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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay