【问题标题】:NodeJS express/request: piping a POST request with body parsing issueNodeJS express/request:管道发送带有正文解析问题的 POST 请求
【发布时间】:2020-06-05 07:56:54
【问题描述】:

我正在尝试通过管道传输由远程服务器处理的请求,以及以下行:

不幸的是,管道不适用于帖子正文,您能建议我如何解决这个问题吗?

self.downloadPriceLists = function (req, res, next) {
  const options = {
    url: `http://${env.MAILER_HOST}:${env.MAILER_PORT}/getpricelist/`,
    method: 'POST',
    json: true,   // <--Very important!!!
    headers: req.headers,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      "Access-Control-Allow-Origin": "*",
    },
    body: {
      userID: req.user.id,
      exportAsOf: req.body.exportAsOf,
      activationDate: req.body.activationDate,
     },
  };
  console.log("options:", options);
  // remoteResponse :: res
  // remoteBody :: body
  const myReq = request.post(options, function (error, remoteResponse, remoteBody) {
    res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition');
    remoteResponse.headers.hasOwnProperty('content-disposition') && res.setHeader('Content-disposition', remoteResponse.headers['content-disposition']);
    remoteResponse.headers.hasOwnProperty('content-type') && res.setHeader('Content-type', remoteResponse.headers['content-type']);
    if (error) {
      console.error('request fail:', error);
      return res.status(500).end('Error');
    }

    console.log('submit successful:', remoteResponse.headers);
    res.pipe(remoteBody);
  });


  // Handle errors
  myReq.on('error', function (err) {
    console.log("++++++++++++sendReq Handle errors:", err);
    res.status(500).end("Error:" + err);
  });
};

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    您不应该管道流而不是标量数据吗? res.pipe(remoteBody); 在我看来确实正确,如果有的话,res.pipe(remoteResponse); 似乎更正确。

    您是否考虑过仅将内部请求的响应写入外部请求而不使用管道?像这样res.json(remoteBody);?

    【讨论】:

    • 基本上用 res.json(remoteBody);和 res.send(remoteBody) 它可以工作,在前端接收到的文件已损坏并且无法打开。即使原始 url 发送一个普通文件。通常通过 get 请求,管道可以解决这个问题。
    猜你喜欢
    • 2017-11-17
    • 1970-01-01
    • 2021-03-12
    • 2019-06-26
    • 1970-01-01
    • 2019-03-15
    • 2021-01-03
    • 1970-01-01
    • 2016-02-11
    相关资源
    最近更新 更多