【问题标题】:Node.js http-proxy: Error response not sent to clientNode.js http-proxy:错误响应未发送到客户端
【发布时间】:2015-09-24 11:36:55
【问题描述】:

我正在使用 proxy.web 转发客户端请求。 当目标服务器启动时,我的代码按预期工作。 当目标服务器关闭时,ECONNREFUSED 错误被捕获并打印到 console.log。我想将该错误发送回客户端,并尝试使用此处提供的示例。不幸的是,错误响应没有到达客户端(尝试了 chrome 和 firefox)。请在下面找到代码。为什么响应没有发送到客户端?

var proxyServer = http.createServer(function(req, res) {

if(req.path === 'forbidden') {
    return res.end('nope');
}

var url_parts = url.parse(req.url);
var extname = path.extname(url_parts.pathname);

    if (extname || url_parts.pathname.length <= 1){
        proxy.web(req, res, {
            target: 'http://localhost:'+config.fileServer.port
        });
    }
    else{
        proxy.web(req, res, {
            target: config.recognitionServer.url
        }, function(e) {
            console.log(e.message);
            if (!res.headersSent) {
                res.writeHead(500, { 'content-type': 'application/json' });
            }
            res.end(JSON.stringify({ error: 'proxy_error', 
                   reason: e.message         
            }));
        });
    }

 }).listen(config.proxyServer.port, function () {
    console.log('Proxy server is listening on port ' 
    + config.proxyServer.port);
 });

【问题讨论】:

    标签: node.js http-proxy


    【解决方案1】:

    一个好的方法是这样的:

    return res.status(500).send({
        error: true,
        message: 'your-error-message'
    });
    

    你的代码重写了:

    proxy.web(req, res, {
        target: config.recognitionServer.url
    }, function (e) {
        console.log(e.message);
        return res.status(500).send({
           error: true,
           message: e.message
        });
    });
    

    【讨论】:

    • 感谢您的回答,米歇尔姆。使用 res.status(500).send() 是不可能的,因为 res 对象不公开 send() 和 status() 方法。我尝试使用其他方法,例如 end()、write(),不幸的是没有成功。服务器向客户端发送错误响应,但客户端永远不会得到它。唤醒客户端的唯一方法是关闭服务器应用程序。但这不是一个好习惯。
    • 我使用的是 express 4.x。事件处理程序范围内的“res”对象没有 send() 和 status() 方法。在外部范围内,它确实有它们。您是否尝试使用 http-proxy 模块运行上面粘贴的代码?
    • 如果我使用 req.pipe() 而不是 proxy.web,则可以在事件处理程序中调用 res.status(500).send(),但响应不会到达客户端要么。
    【解决方案2】:

    问题已在客户端解决 :) 客户端代码是使用 XMLHttpRequest 的 JS(在 FF 和 Chrome 上测试)。错误响应到达“onload”事件处理程序,而不是“onerror”。 “onload”处理函数需要检查响应状态。如果错误状态 (500),继续错误处理程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 2011-06-13
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多