Node.js http-代理 : Error response not sent to client

标签 node.js http-proxy

我正在使用 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);
 });

最佳答案

一个好的方法是这样的:

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
    });
});

关于Node.js http-代理 : Error response not sent to client,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31260825/

相关文章:

c# - HTTPWebRequest.GetResponse() 因通过透明代理的经过身份验证的请求而失败

node.js - 应提供反向代理 header

node.js - 如何从 CLI 停止 Yarn Package Manager 脚本

javascript - 处理可选参数的 Node 模块

javascript - 运行 gulp 任务时 Gulp-livereload 错误

javascript - 使用 node.js http-proxy 测量流量

node.js - npm 启动 Microsoft JScript 运行时错误 800A138F 预期对象

node.js - 如何从名称中包含 @ 的 NPM 包安装 @types

python - 在 Ubuntu 中关闭代理导致 python 网络请求失败

reactjs - React App-createProxyMiddleware不是函数