How to send urlencoded data using Axios
By Flavio Copes
Learn how to send urlencoded data with Axios using the qs module's stringify() method and the application/x-www-form-urlencoded content-type header.
To send urlencoded data using Axios, stringify your data with the qs module and set the content-type header to application/x-www-form-urlencoded. Let me show you the full setup.
I had this problem: an API I had to call from a Node.js app was only accepting data using the urlencoded format.
I had to figure out this problem: how to send urlencoded data using Axios?
What is urlencoded data?
It’s the format HTML forms use when they submit: key/value pairs separated by =, joined by &:
item1=value1&item2=value2
Axios doesn’t produce this format on its own. When you pass a plain JavaScript object as data, Axios serializes it to JSON. An API that expects form data will reject that body, or parse it into nothing.
The qs module
The first thing we need to do is to install the qs module. It’s a cool querystring parsing and stringifying library with some added security:
npm install qs
Then we need to import the qs module along with the Axios import, of course:
const qs = require('qs')
const axios = require('axios')
If you use ES Modules, use
import qs from 'qs'
import axios from 'axios'
The request
Next, the Axios code. Check my full Axios tutorial if you are not familiar with it.
In short, we need to use the full form for the Axios request. Not axios.post() but axios().
Inside there, we use the stringify() method provided by qs and we wrap the data into it. We then set the content-type header:
axios({
method: 'post',
url: 'https://my-api.com',
data: qs.stringify({
item1: 'value1',
item2: 'value2'
}),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
}
})
qs.stringify() turns the object into the string the server expects:
qs.stringify({ item1: 'value1', item2: 'value2' })
//'item1=value1&item2=value2'
It handles nested objects too, using the bracket notation servers like PHP and Rails understand:
qs.stringify({ user: { name: 'Flavio' } })
//'user%5Bname%5D=Flavio', the encoded form of user[name]=Flavio
A pitfall to avoid
Setting the header alone is not enough. If you set content-type to urlencoded but pass a plain object as data, Axios still sends a JSON body. The header claims one format, the body carries another, and the server fails to parse the request.
Always pass the already-stringified data, like in the example above. If the API responds with an error saying a required field is missing even though you’re sending it, this mismatch is the first thing to check.
Related posts about js: