How to send application/x-www-form-urlencoded format data with axios in vue

Today I had a problem passing arguments using axios, but the server didn’t receive the data. After repeated debug with postman I found that the problem was the format of the parameters: the api only supports getting parameters in application/x-www-form-urlencoded format data and axios serializes JavaScript objects to JSON by default.

This is my original codes:

axios.post('/user', {
	'firstName': 'paul',
	'lastName': 'fred'
}).then(function (response) {
	console.log(response);
}).catch(function (error) {
	console.log(error);
});

To send data in the application/x-www-form-urlencoded format instead, we can use 2 following options below.

  • First option: qs library
var qs = require('qs');
axios.post('/user', qs.stringify({'firstName': 'paul', 'lastName': 'fred'}));
  • Second option: URLSearchParams api
var params = new URLSearchParams();
params.append('firstName', 'paul');
params.append('lastName', 'fred');
axios.post('/user', params);

Both 2 options work well for me, pls let me know if you have better options. If you want to know about encoding format of POST method, click here.

RSS