How to Send Form URL Encoded Data in Axios
Sending application/x-www-form-urlencoded data with
Axios requires formatting the payload so the receiving server parses it
as standard form submissions rather than default JSON. This article
explains the standard methods for encoding payloads in Axios using
native browser APIs like URLSearchParams, automatic object
serialization, and the qs library for nested data
structures.
Method 1: Using
URLSearchParams (Standard/Modern)
The native URLSearchParams interface is built into
modern browsers and Node.js. When passed as the data payload, Axios
automatically sets the Content-Type header to
application/x-www-form-urlencoded.
import axios from 'axios';
const params = new URLSearchParams();
params.append('username', 'johndoe');
params.append('password', 'secret123');
axios.post('https://example.com/api/login', params)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});Alternatively, you can initialize URLSearchParams
directly with an object:
const params = new URLSearchParams({
username: 'johndoe',
password: 'secret123'
});
await axios.post('https://example.com/api/login', params);Method 2:
Using the qs Library (Best for Nested Objects)
URLSearchParams does not serialize nested objects or
complex arrays effectively. The qs library handles deep
object serialization into standard URL-encoded strings.
import axios from 'axios';
import qs from 'qs';
const data = {
user: {
name: 'John Doe',
email: 'john@example.com'
},
roles: ['admin', 'editor']
};
axios.post('https://example.com/api/users', qs.stringify(data), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => console.log(response.data))
.catch(error => console.error(error));Method 3: Built-in Axios Automatic Serialization (Axios v1.x+)
In modern versions of Axios, setting the Content-Type
header to application/x-www-form-urlencoded allows you to
pass a standard JavaScript object directly. Axios will automatically
serialize the object.
import axios from 'axios';
const data = {
username: 'johndoe',
password: 'secret123'
};
axios.post('https://example.com/api/login', data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => console.log(response.data))
.catch(error => console.error(error));Method 4: Using
Node.js Built-in querystring
In older Node.js environments where external dependencies are
restricted, use the built-in querystring module:
const axios = require('axios');
const querystring = require('querystring');
const data = querystring.stringify({
username: 'johndoe',
password: 'secret123'
});
axios.post('https://example.com/api/login', data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => console.log(response.data))
.catch(error => console.error(error));