【问题标题】:Node.JS proxy using request module使用请求模块的 Node.JS 代理
【发布时间】:2016-12-09 22:36:12
【问题描述】:

我有一个 Express.JS 应用程序,它使用请求节点模块对路由进行代理调用。这在 NodeJS V0.10.28 中运行良好;但是,升级到 NodeJS V4.4.7 导致此操作失败 - 抛出错误“错误:结束后写入”。

我是 NodeJS 的新手;非常感谢您的帮助。

var bodyParser=require('body-Parser');
app.use(bodyParser.json({limit: '100mb'}));
app.use(bodyParser.urlencoded({extended: false}));

....
....

app.use('/relay', function (req, res) {
        var request = require('request'),
            proxyUrl = 'http://abc.proxy.xyz:12345',
            apiEndPoint = "https://aaa.bbb.ccc/svc";

        req.pipe(request.post(apiEndPoint,{ proxy: proxyUrl, form: req.body}, function (error, response, body) {

            if (error) {
                console.log(error)
            } else {
                console.log("No error here.")
            }

            res.end();

        })).pipe(res);   
});

【问题讨论】:

    标签: node.js express proxy request


    【解决方案1】:

    为了后代,这是我的解决方案,以防其他人遇到同样的问题。

    问题在于中间件 body-parser 的使用:body-parser 读取请求以完成 - 因此流已到达其末尾。因此, req.pipe() - 在问题中显示的 /relay 路由中 - 没有任何可读取的内容,并且不会重新启动流。

    不过,返回的错误消息“结束后写入”是很模糊的。为什么我在 Node.JS V0.10.28 中没有遇到这个问题也是一个谜。报告的问题在 V4.4.7 中发现

    因此,为了解决 body-parser 问题,我将 /relay 路由移到了对 body-parser 的调用之上:

    app.use('/relay', function (req, res) {
            var request = require('request'),
                proxyUrl = 'http://abc.proxy.xyz:12345',
                apiEndPoint = "https://aaa.bbb.ccc/svc";
    
            req.pipe(request.post(apiEndPoint,{ proxy: proxyUrl, form: req.body}, function (error, response, body) {
    
                if (error) {
                    console.log(error)
                } else {
                    console.log("No error here.")
                }
    
                res.end();
    
            })).pipe(res);   
    });
    
    ....
    ....
    
    var bodyParser=require('body-Parser');
    app.use(bodyParser.json({limit: '100mb'}));
    app.use(bodyParser.urlencoded({extended: false}));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      • 2020-04-27
      • 1970-01-01
      • 2022-01-19
      相关资源
      最近更新 更多