How to use Axios' create() Method with POST Requests

Mar 1, 2021

Axios has a neat tool, create(), that allows you to customize your HTTP requests if you need to make multiple requests to the same domain. The create() function allows you to create an instance with pre-populated Axios options.

By specifying the url and the type of request in the instance, you don't need to use the specific axios function calls like post(). Instead, you use request() and specify the other configuration properties that create() was not responsible for, like the information to be sent in the data property. You can create a custom instance for a POST request as shown below:

const instance = axios.create({
  url: '/post',
  baseURL: 'https://httpbin.org',
  method: 'POST',
  timeout: 1000
});

let res = await instance.request({
  data: {
    name: 'Masteringjs.io',
    email: 'Masteringjs@io'
  }
});

res.data.json // ↓
// { email: 'Masteringjs@io', name: 'Masteringjs.io' }

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Axios Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!