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.
npm install qs
Next, we need to import the qs
module and the axios
library in our code:
const qs = require('qs');
const axios = require('axios');
If you are using ES Modules, you can import them like this:
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:
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