Node.js http-proxy: error message not sent to client

I am using proxy.web to forward client requests. When the target server is running, my code works as expected. When the destination server is down, the ECONNREFUSED error is broken and printed to console.log. I would like to send this error back to the client and have tried using the sample provided here. Unfortunately the error response doesn't come to the client (tried both chrome and firefox). Below is the code. Why isn't a response 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);
 });

      

+3


source to share


2 answers


Problem solved on client side :) Client code is JS using XMLHttpRequest (tested on FF and Chrome). The response to the error goes to the "onload" event handler, not the "onerror" event. The "onload" handler function should check the status of the response. If the error status is (500), continue with the error handler.



0


source


A good approach is this:

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

      



Your code has been 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
    });
});

      

+2


source







All Articles