【问题标题】:How to troubleshoot hanging /POST request with a body to Express如何解决挂起 /POST 请求与 Express 的正文
【发布时间】:2021-07-12 14:38:30
【问题描述】:

我希望有人能指出我正确的方向。我正在使用http 发送请求以表达并且请求只是挂起,如果我重新启动我的快速服务器,它将返回 500 内部服务器错误,或者以“请求中止”重新启动客户端。奇怪的是,似乎只有当我提交带有正文的 /POST 请求时 - 但没有正文的 POST 请求可以正常工作。

这是我的要求:

const the_Headers = {
  Authorization: "Bearer <token>",
  "x-custom-header": "custom-header-val",
  "content-type": "application/json",
  "content-length": "21",
}
const data = "{\"test\":\"123\"}"
const result = await new Promise((resolve,reject) => {
  const request = http.request(
    new URL("http://localhost/some/path"), 
    {headers: the_Headers, method: POST}, 
    (res) => {
      res.setEncoding('utf8');
      let responseBody = '';

      res.on('data', (chunk) => {
        responseBody += chunk;
      });

      res.on('end', () => {
        resolve({body: responseBody});
      });
    });
    request.on('error', (err) => {
      reject({statusCode: 500, error: err});
    });

    if (data)
      request.write(data);
    
    request.end();
  })
});

这是我的路由器:

router.post("/some/path",    
    async (req, res) => {
        //  makes it to this breakpoint with empty(no body) POST request
        res.status(200)
            .json({ message: "body is: " + req.body.toString()});
})

这是DEBUG=express:*的输出

express:router dispatching POST /some/path +7s
express:router query  : /some/path +1ms
express:router expressInit  : /some/path +0ms
express:router urlencodedParser  : /some/path +0ms
express:router jsonParser  : /some/path +1ms
... (does not proceed from here - so assuming problem with jsonParser)

【问题讨论】:

    标签: express http-headers http-post


    【解决方案1】:

    这是内容长度不匹配。

    当数据为 14 时,Header 传递的长度为 21。这导致 jsonParser 中的 readstream 永远不会调用 end() 方法。

    【讨论】:

      猜你喜欢
      • 2014-04-30
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 2023-04-10
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      相关资源
      最近更新 更多