在中间件中获取响应状态码
Get response status code in a middleware
我正在构建一个应用程序,我试图在其中为每个请求构建我自己的日志记录系统。
对于每个请求,我想记录时间戳、使用的方法、路由以及最后发送给客户端的响应代码。
我目前有以下代码:
// 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();
}
不幸的是,即使我这样做 res.status(201).send('hello world')
它总是会捕获 200
状态码...
有没有办法捕获任何传出到客户端的响应并获取其状态代码?
据我了解,您需要在响应中添加一些状态代码
您可以像这样简单地设置状态码
let code = {
serverError:500,
forbidden:401
}
res.status(code.serverError).json({
message:'Server error'
})
如果要在中间件中设置
middleware.js
const statuscode = function middleware(req,res,next){
let code = {
serverError:500,
forbidden:401
}
req.statusCode =code.serverError
next()
}
module.exports = {
statuscode
}
在index.js
const middleware = require('./middleware');
app.get('/',middleware.statuscode, (req, res, next) => {
console.log("Code from middleware",req.statusCode);
res.send('hello world !');
});
创建中间件并覆盖发送函数
app.use(function (req, res) {
var send = res.send;
res.send = function (body) {
// Do something
send.call(this, body);
};
});
使用响应中的 finish
事件确实是一个很好的解决方案。问题出在 finish
事件回调中,我无法使用箭头函数,因为它不会绑定 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();
}
快递回复extends the Node.js http.ServerResponse
, so you can listen for the 'finish'
事件:
Event: 'finish'
Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet.
app.use((req, res, next) => {
res.on('finish', () => {
console.log(`Responded with status ${res.statusCode}`);
});
next();
});
我正在构建一个应用程序,我试图在其中为每个请求构建我自己的日志记录系统。
对于每个请求,我想记录时间戳、使用的方法、路由以及最后发送给客户端的响应代码。
我目前有以下代码:
// 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();
}
不幸的是,即使我这样做 res.status(201).send('hello world')
它总是会捕获 200
状态码...
有没有办法捕获任何传出到客户端的响应并获取其状态代码?
据我了解,您需要在响应中添加一些状态代码
您可以像这样简单地设置状态码
let code = {
serverError:500,
forbidden:401
}
res.status(code.serverError).json({
message:'Server error'
})
如果要在中间件中设置
middleware.js
const statuscode = function middleware(req,res,next){
let code = {
serverError:500,
forbidden:401
}
req.statusCode =code.serverError
next()
}
module.exports = {
statuscode
}
在index.js
const middleware = require('./middleware');
app.get('/',middleware.statuscode, (req, res, next) => {
console.log("Code from middleware",req.statusCode);
res.send('hello world !');
});
创建中间件并覆盖发送函数
app.use(function (req, res) {
var send = res.send;
res.send = function (body) {
// Do something
send.call(this, body);
};
});
使用响应中的 finish
事件确实是一个很好的解决方案。问题出在 finish
事件回调中,我无法使用箭头函数,因为它不会绑定 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();
}
快递回复extends the Node.js http.ServerResponse
, so you can listen for the 'finish'
事件:
Event: 'finish'
Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet.
app.use((req, res, next) => {
res.on('finish', () => {
console.log(`Responded with status ${res.statusCode}`);
});
next();
});