2016-07-29 84 views
1

我想保存我的服务器提供的4XX和5XX错误的数量。我采取的方法是创建一个明确的中间件获得的StatusCode响应如何访问发送到Expressjs应用程序客户端的响应代码

const fooMiddleware = (req, res, next) => { 
    req.stats.totalRequestsServed += 1; 

    // I want to access the status code sent to the client here 
    console.log('status code', res.statusCode); 
    next(null); 
}; 

我在上面使用的代码,但我总是得到一个200状态代码,即使我在我的路线上硬编码res.status(401).end()

回答

1

你的答案可以发现here

app.use(function (req, res, next) { 
    function afterResponse() { 
     res.removeListener('finish', afterResponse); 
     res.removeListener('close', afterResponse); 

     // do smth after res.send 
     console.log(res.status); 
    } 

    res.on('finish', afterResponse); 
    res.on('close', afterResponse); 

    // do smth before request eventually calling `next()` 
    next(); 
}); 

恕我直言,勾手不透明度。这需要一些“特殊”情况。
对于记录4xx和5xx错误,错误处理程序更好。

app.get('/smth', function(req, res, next){ 
    if (!smth-check) 
     return next(new HttpError(401, 'Error-text')); // it's custom error class 
    ... 
}) 

app.use(function(err, req, res, next)) { 
    if (err instance of HttpError) 
     console.log(err.status); 
    ... 
}); 

关于custom errorHttpError您可以阅读here

+0

第二种方法的问题是我们并不总是使用next。我喜欢更独立的解决方案。 –

0

我发现了一个叫做on-finished是管理,这也增加了听众。它可以像这样使用:

const onFinished = require('on-finished'); 

const middleware = (req, res, next) => { 

    onFinished(res, (err, res) => { 
    // do smth after res.send 
    }); 

    // do smth before request eventually calling `next()` 
    next(null); 
}; 
0

你的逻辑是正确的,你只需要调用next之前获得的状态,让其他中间件/路线可以设置状态码:

const fooMiddleware = (req, res, next) => { 
    req.stats.totalRequestsServed += 1; 
    next(); 
    console.log('status code', res.statusCode); 
};