Reputation: 193
I'm using proxy.web to forward client requests. When destination server is up, my code works as expected. When destination server is down, ECONNREFUSED error is catch and printed to console.log. I would like to send that error back to the client, and tried using the sample provided here. Unfortunately, the error response does not arrive to the client (tried both chrome and firefox). Please find below code. Why does the response not sent to the client ?
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);
});
Upvotes: 5
Views: 4309
Reputation: 193
Problem was solved on client side :) Client code is JS using XMLHttpRequest (tested on FF and Chrome). The error response arrives to "onload" event handler, not to "onerror". The "onload" handler function needs to check response status. If error status (500), continue with error handler.
Upvotes: 1
Reputation: 14590
A good approach is this:
return res.status(500).send({
error: true,
message: 'your-error-message'
});
Your code rewritten:
proxy.web(req, res, {
target: config.recognitionServer.url
}, function (e) {
console.log(e.message);
return res.status(500).send({
error: true,
message: e.message
});
});
Upvotes: 3