如何使用connect框架捕获404错误

时间:2014-02-12 10:22:30

标签: node.js

如果我们编写一个代理到另一个位置的nodejs程序,如何捕获404错误。

代码看起来像这样

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

couchForward模块将请求转发给couch对象中指定的另一个网址

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

    }
}

我写了

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

但res.statusCode始终为200,原因不明,即使目标网址不存在

0 个答案:

没有答案