How to send axios post with application / x-www-form-urlencoded?

Viewed 2102

How to send axios post with application / x-www-form-urlencoded?

I need to send a refresh token, but when requested, an empty object is sent, although if you look in "userData.data.refresh_token", then the token is definitely there

const params = new URLSearchParams();
const test = params.append("refresh_token", userData.data.refresh_token);

console.log(test) // undefined
console.log(userData) // token not empty
axios.post(`${API_URL}/api/login_check`, test, (res) => {
  login(res);
});
2 Answers
const axios = require('axios')

Try this code:

/* ... */

const params = new URLSearchParams()
params.append('name', 'Akexorcist')
params.append('age', '28')
params.append('position', 'Android Developer')
params.append('description', 'birthdate=25-12-1989&favourite=coding%20coding%20and%20coding&company=Nextzy%20Technologies&website=http://www.akexorcist.com/')
params.append('awesome', true)

const config = {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
}

axios.post(url, params, config)
  .then((result) => {
    // Do somthing
  })
  .catch((err) => {
    // Do somthing
  })

Official link: https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

Below is from the link above.


In a browser, you can use the URLSearchParams API as follows:

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

Alternatively, you can encode data using the qs library:

const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
Related