我正在使用 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/