使用中间件来代替app.get中的console.log。
示例代码如下:
const express = require('express');
const app = express();
// 定义中间件
function logger(req, res, next) {
console.log(`[${new Date().toISOString()}] ${req.method}: ${req.url}`);
next();
}
// 将中间件应用于app
app.use(logger);
// 当访问'/hello'时,输出“hello world”
app.get('/hello', (req, res) => {
res.send('hello world');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
在上述示例中,我们定义了一个中间件logger
,用于输出请求的时间、方法和URL。然后我们将这个中间件应用于app中,这样所有的请求都会经过这个中间件。在中间件中使用console.log就不会出现问题了。