how to post data in node.js with content type ='application/x-www-form-urlencoded'
request
supports application/x-www-form-urlencoded
and multipart/form-data
form uploads. For multipart/related
refer to the multipart API.
application/x-www-form-urlencoded (URL-Encoded Forms)
URL-encoded forms are simple:
const request = require('request');
request.post('http:/url/rest/login', {
form: {
username: 'xyzzzzz',
password: 'abc12345#'
}
})
// or
request.post('http:/url/rest/login').form({
username: 'xyzzzzz',
password: 'abc12345#'
})
// or
request.post({
url: 'http:/url/rest/login',
form: {
username: 'xyzzzzz',
password: 'abc12345#'
}
}, function (err, httpResponse, body) { /* ... */ })
See: https://github.com/request/request#forms
Or, using request-promise
const rp = require('request-promise');
rp.post('http:/url/rest/login', {
form: {
username: 'xyzzzzz',
password: 'abc12345#'
}
}).then(...);
See: https://github.com/request/request-promise#api-in-detail
If you are using axios package, Here is the solution.
If you have the headers as Content-type: 'application/x-www-form-urlencoded'
then you will call post API as
const response: any = await axios.post(URL, bodyData, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
URL is you API url like http//YOUR_HOST/XYZ..., and
bodyData is the data which you want to send in post API,
Now how will you pass it ?
Suppose you have data as object, so you have to encode it as url, let me show you
let data = {
username: name,
password: password
}
then your bodyData will be like
let bodyData = `username=${name}&password=${password}`
This is the way you can pass your data in body if header is
Content-type: 'application/x-www-form-urlencoded'
If you have a huge data which you cannot encode it manually then you can use qs module
run command npm i qs
and in your file
const qs = require('qs');
...
let data = {
username: name,
password: password,
manyMoreKeys: manyMoreValues
}
let bodyData = qs.stringify(data);