在中间件中获取响应状态代码

noo*_*ook 2 javascript middleware http-status-codes node.js express

我正在构建一个应用程序,其中我试图为每个请求构建自己的日志记录系统。

对于每个请求,我想记录时间戳,使用的方法,路由,最后是已发送到客户端的响应代码。

我现在有以下代码:

// index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(bodyParser.json());
app.use(cors());

app.use(require('./lib/logging'));

app.get('/', (req, res, next) => {
  res.send('hello world !');
});

app.listen(3001);

// ./lib/logging.js
const moment = require('moment');
const chalk = require('chalk');
const log = console.log;

module.exports = (req, res, next) => {
  let now = `[${chalk.green(moment().format('HH:mm:ss'))}]`;
  let method = chalk.magenta(req.method);
  let route = chalk.blue(req.url);
  let code = chalk.yellow(res.statusCode); // Always 200
  log(`${now} ${method} request received on ${route} ${code}`);
  next();
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,即使我这样做,res.status(201).send('hello world')它始终会捕获200状态代码...是否可以捕获任何发送到客户端的响应并获取其状态代码的方法?

Ale*_*lec 7

Express 响应扩展了 Node.js http.ServerResponse,因此您可以监听'finish'事件:

事件:'完成'

发送响应时发出。更具体地说,当响应标头和正文的最后一段已移交给操作系统以通过网络传输时,将发出此事件。这并不意味着客户端还没有收到任何东西。

app.use((req, res, next) => {
  res.on('finish', () => {
    console.log(`Responded with status ${res.statusCode}`);
  });
  next();
});
Run Code Online (Sandbox Code Playgroud)


noo*_*ook 6

使用finish响应中的事件确实是一个很好的解决方案。问题出在finish事件回调中,我只是不能使用arrow函数,因为它不会绑定this关键字,而这被存储了响应数据。

所以下面的代码正在工作:

// ./lib/logging.js

const moment = require('moment');
const chalk = require('chalk');
const log = console.log;

module.exports = (req, res, next) => {
  let now = `[${chalk.green(moment().format('HH:mm:ss'))}]`;
  let method = chalk.magenta(req.method);
  let route = chalk.blue(req.url);
  res.on('finish', function() {
    let code = chalk.yellow(this.statusCode);
    log(`${now} ${method} request received on ${route} with code ${code}`);
  })

  next();
}
Run Code Online (Sandbox Code Playgroud)