我正在开发一个网络客户端,它使用 Node.js's request module 请求服务器。发送的请求是POST请求。服务器是使用 Express 用 Node.js 编写的。 NGINX 还有另一层充当代理并将请求重定向到用 Node.js 编写的服务器。
问题是: 每当我尝试发送请求时,如果没有显式定义任何 header ,NGINX 就会发送内容长度的 html 错误,#411(需要长度)。然而,当我尝试使用浏览器和curl发送类似的请求时,一切正常。示例代码如下:
request.post(url, function(err, response, data) {
if(err) {
console.log(err);
} else {
console.log(data);
}
}).form({'data':'someValue'})
此外,现在当我将 content-length 添加到请求 header 时,NGINX 挂起,看来 NGINX 正在等待更多数据到达。 NGINX 不会将请求转发到服务器。
添加了包含内容长度的选项
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'});
我在发送请求时做错了什么?
最佳答案
我找到了解决方案。
我正在发送 JSON 数据。错误是我使用了 form()
函数,它将 header 设置为“Content-type: application/x-www-form-urlencoded; charset=utf-8”。引用自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.
一旦我使用了 json
选项,并删除了 form()
函数,它就开始正常工作了。
关于Node.js 请求模块 + NGINX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14910880/