Reputation: 5253
I am developing a web-client, which requests a server using Node.js's request module. Requests sent are POST requests. Server is written in Node.js using Express. There is another layer of NGINX which acts as proxy and redirects requests to server written in Node.js.
Problem is: Whenever i try to send request, without explicitly defining any header, NGINX is sending html error for content-length, #411 (Length required). Wherease, when I try I to send similar request using browser and curl, everything works fine. Sample code is as follows:
request.post(url, function(err, response, data) {
if(err) {
console.log(err);
} else {
console.log(data);
}
}).form({'data':'someValue'})
Further, now when I added content-length to the header of request, then NGINX hangs, it seems NGINX is waiting for more data to arrive. NGINX do not forwards the request to server.
Options added to include content-length
var dataObj = {'data' = 'someValue'};
var options = {
'uri' = url
, 'headers' = {
'Content-Length' = JSON.stringify(dataObj).length
}
};
request.post(options, function(err, response, data) {
if(err) {
console.log(err);
} else {
console.log(data);
}
}).form({'data':'someValue'});
What am I doing wrong in sending request?
Upvotes: 2
Views: 1231
Reputation: 5253
I found the solution.
I was sending JSON data. Mistake is I was using form()
function, which sets header to "Content-type: application/x-www-form-urlencoded; charset=utf-8". Quoting from Request documentation
form - when passed an object this will set body but to a querystring representation of value and adds Content-type: application/x-www-form-urlencoded; charset=utf-8 header. When passed no option a FormData instance is returned that will be piped to request. auth - A hash containing values user || username, password || pass, and sendImmediately (optional). See documentation above. json - sets body but to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as json.
Once I used json
option, and removed form()
function, it started working properly.
Upvotes: 2