Node.js 请求模块 + NGINX

标签 node.js nginx request httprequest

我正在开发一个网络客户端,它使用 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/

相关文章:

http - http请求调用方法的难点

node.js - express.js + 手写笔 : Automatic stylus compiling doesn't work

php - 找不到文件 - Docker 中的 Nginx

nginx - Windows 10 单节点 Kubernetes 基础设施上 docker-desktop 社区版上的 MetalLB 外部负载均衡器

node.js - 多个异步请求

node.js - Node JS 通过 HTTP 上传文件流

mysql - 如何调试 knex.js?不必污染我的数据库

javascript - 如何为我的应用程序使用带有 `npm start` 的 Node 检查器?

javascript - 字符串上下文中的新日期在 Firefox 中不起作用

nginx - 如何编写 Nginx 模块?