如何访问发送给Expressjs应用程序客户端的响应代码

我想保存由我的服务器提供的4XX和5XX错误的数量。 我采取的方法是创build一个快速的中间件,以获得statusCode响应

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()在我的路线。

你的答案可以在这里find

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

Imho,钩子是不透明的。 这是需要一些“特殊”的情况。
error handling程序更好地logging4xx和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 error HttpError你可以在这里阅读

我发现一个名为on-finished的软件包pipe理这个也添加了一个监听器。 可以这样使用:

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

你的逻辑是对的,你只需要获得状态之前再打电话,以便其他中间件/你的路由可以设置状态码:

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