本文介绍了nodejs api不转发从另一个服务收到的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个 nodejs api 来监听 http 请求,然后添加一些标头值并将其转发到不同服务器中的另一个 Restful 服务.当响应返回时,我会将相同的响应转发给请求者而不做任何修改.所以基本上这个 api 将用作转发代理.

I developed a nodejs api to listen to http requests then add some header values and forward it to another Restful service in different server. When the response returns, I will forward same response to requester without doing any modification. so basically this api will work as a forward proxy.

我使用下面的代码将响应转发给请求者,它返回数据,但是我们的一个响应包含一个附件(pdf 文件),该附件将始终作为空文件/损坏的文件接收到请求者.有人可以帮我解决这个问题吗?

I used below code to forward the response to requester, It returns data however one of our response includes an attachment(pdf file) which will always receive to requester as an empty file/corrupted. Can anybody please help me to resolve this?

app.use('/', function(req, res, next){

    var request = require('request');

    var url={{someurl}}

    var option = {
        method:req.method,
        json:data,
        headers:{
           "Content-Type": "application/json",
           "Cookie":result
        };
    };
    request(URL, option, function (error, response, body) {

        if (error) {
            res.status("500").send(error);
            res.end(err);
        }else{
            if (req.method=='GET'){
                res.set(response.headers);
            }

            res.status(response.statusCode).send(body);
            res.end(response);
        }
    })
  });

推荐答案

我找到了这个问题的解决方案.在选项中我必须添加编码:null,否则正文将转换为字符串.当正文转换为字符串时,文件将被损坏.

I found the solution for this issue. in option I have to add encoding: null, otherwise body will be converted to string. when the body converted to string, file will be corrupted.

这篇关于nodejs api不转发从另一个服务收到的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:14