【问题标题】:Send a File From Api Server to NodeJs to Browser将文件从 Api 服务器发送到 NodeJs 到浏览器
【发布时间】:2017-08-01 11:45:19
【问题描述】:

我有一个 API 服务器和 NodeJs 服务器,当请求一个文件时,NodeJs 将请求重定向到 API 服务器

API 服务器将文件作为原始数据发送到 NodeJs Nodejs 将文件重定向到浏览器

但是当我使用 Wire Shark 检查网络数据时,浏览器收到的数据包不是来自 API Server 的原始数据包(适用于文本文件,但不适用于图像、视频、pdf、doc 等)

router.get('/GetCaseSupportDocument', function (req, res) {

    var MyJsonData = {
         DocId:parseInt(req.query.DocId) || 0
    };

    request({
        url: 'http://somedomain/someurl', //URL to hit
        method: 'POST',
        json: MyJsonData

    }, function (error, response, body) {
        if (error) {
              res.status(200).send('Failed');
        } else {
              res.status(200).send(body);
            }
    })

});

谁能说出为什么它会在 NodeJ 和浏览器之间发生变化? 这种传输方式有没有更好的解决方案?

找到解决方案后更新。这行得通

    router.get('/GetCaseSupportDocument', function (req, res) {

        var MyJsonData = {
           DocId:parseInt(req.query.DocId) || 0

        };

        request({
            url: Url.CaseService + 'GetCaseSupportDocument', //URL to hit
            method: 'POST',
            json: MyJsonData
        }).pipe(res);

})

【问题讨论】:

  • 只是一个小评论:如果遇到错误,您可能不应该返回状态 200。如果您可以更清楚地隔离错误的类型,您可以准确地弄清楚它应该是什么,但在此期间我只会返回 500。
  • @HomerPlata 。我只想向外部世界隐藏应用程序中 API 服务器的存在。数据 y 返回“失败”。无论如何,谢谢...就像我说的那样,我得到了答复。但它在某些字符开始后发生了某种变化,并且在文本文件的情况下效果很好

标签: node.js


【解决方案1】:

您可以尝试使用流的简单代理:

router.get('/GetCaseSupportDocument', function (req, res) {
  var MyJsonData = {
    DocId: parseInt(req.query.DocId) || 0
  };

 // updated the response
 request({
    url: 'http://somedomain/someurl', //URL to hit
    method: 'POST',
    json: MyJsonData
  }).pipe(res);

});

有关代理的更多详细信息,您可以在 request 文档 https://github.com/request/request 上找到

【讨论】:

  • 尝试过这种方式,但我得到了这个错误----stream.js:74 throw er; // 管道中未处理的流错误。 ^ 错误:在 ClientRequest.OutgoingMessage.write (_http_outgoing.js:439:15) 结束后写入
  • req.pipe 一开始是不需要的..nw 它有效...用答案编辑了我的问题
猜你喜欢
  • 1970-01-01
  • 2020-07-30
  • 2017-08-18
  • 2020-06-30
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
相关资源
最近更新 更多