/

How to Send URL Encoded Data using Axios

How to Send URL Encoded Data using Axios

In this tutorial, we will learn how to send URL encoded data using the Axios library in a Node.js application.

Problem Statement

When working with an API that only accepts data in the URL encoded format, we need to find a way to send the data using Axios.

Solution

To solve this problem, we will need to install the qs module, which is a querystring parsing and stringifying library with added security.

1
npm install qs

Next, we need to import the qs module and the axios library in our code:

1
2
const qs = require('qs');
const axios = require('axios');

If you are using ES Modules, you can import them like this:

1
2
import qs from 'qs';
import axios from 'axios';

Assuming you are already familiar with Axios, we will proceed with the code required to send URL encoded data.

Instead of using the shorthand method axios.post(), we need to use the full form of the Axios request by calling axios().

Within this function call, we will use the stringify() method provided by the qs module to wrap our data. Additionally, we will set the content-type header to application/x-www-form-urlencoded;charset=utf-8.

Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
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'
}
})

And that’s it! Now you know how to send URL encoded data using Axios in your Node.js application.

Tags: axios, node.js, url encoded data, qs module