Node.js: How to send headers with form data using request module?
I think it's just because you have forgot HTTP METHOD. The default HTTP method of request is GET.
You should add method: 'POST'
and your code will work if your backend receive the post method.
var req = require('request');
req.post({
url: 'someUrl',
form: { username: 'user', password: '', opaque: 'someValue', logintype: '1'},
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
'Content-Type' : 'application/x-www-form-urlencoded'
},
method: 'POST'
},
function (e, r, body) {
console.log(body);
});
This should work.
var url = 'http://<your_url_here>';
var headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
'Content-Type' : 'application/x-www-form-urlencoded'
};
var form = { username: 'user', password: '', opaque: 'someValue', logintype: '1'};
request.post({ url: url, form: form, headers: headers }, function (e, r, body) {
// your callback body
});
I found the solution to this problem and It should work. I'm sure about this because I also faced the same problem
here is my solution----->
var request = require('request');
//set url
var url = 'http://localhost:8088/example';
//set header
var headers = {
'Authorization': 'Your authorization'
};
//set form data
var form = {first_name: first_name, last_name: last_name};
//set request parameter
request.post({headers: headers, url: url, form: form, method: 'POST'}, function (e, r, body) {
var bodyValues = JSON.parse(body);
res.send(bodyValues);
});
I've finally managed to do it. Answer in code snippet below:
var querystring = require('querystring');
var request = require('request');
var form = {
username: 'usr',
password: 'pwd',
opaque: 'opaque',
logintype: '1'
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'http://myUrl',
body: formData,
method: 'POST'
}, function (err, res, body) {
//it works!
});