0

How to catch 404 errors if we write a nodejs program that proxies to another location.

The code looks like this

 connect()
.use(couchForward(couch))
.listen(port);

The couchForward module forwards the request to another url specified in the couch object

module.exports = function(couch) {
    var proxy = new httpProxy.HttpProxy(couch),
        couchTarget = couch.target;

    return function(req, res, next) {
        console.log('Received request: ' + req.url);

        req.headers['host'] = couchTarget.host + ':' + couchTarget.port;
        req.headers['authorization'] = couch.credentials;
        req.headers['x-forwarded-ssl'] = util.isSecureForwardedRequest(req);
        var forwardedFor = req.headers['x-forwarded-for'];
        req.headers['x-real-ip'] = forwardedFor
            ? forwardedFor.split(',',1)[0]
            : req.connection.remoteAddress;
        req.url = couch.path + req.url;

        console.log('Proxying to: ' + req.url);

        var startTime = new Date().getTime();

        proxy.proxyRequest(req, res);

        var endTime = new Date().getTime();

        var respTime = endTime - startTime;

        console.log('Response time for ' + req.url + ': ' + respTime + 'ms');

        next();

    }
}

I wrote

 connect()
.use(couchForward(couch))
.use(function(req,res){console.log("Broke!" + res.statusCode)})
.listen(port);

But the res.statusCode is always 200 for unknown reasons even if the target url does not exist

Nandish A
  • 1,645
  • 5
  • 26
  • 41

0 Answers0