面试题答案
一键面试Node.js中间件概念
Node.js中间件是在请求处理流程中,处于应用程序和最终响应之间的函数。它可以对请求进行预处理、后处理,执行通用任务(如日志记录、身份验证、错误处理等),增强应用程序的功能和灵活性,且多个中间件可以依次串联工作。
Express框架实现记录请求时间中间件代码示例
const express = require('express');
const app = express();
// 定义中间件
const logRequestTime = (req, res, next) => {
const now = new Date().toISOString();
console.log(`Request received at ${now}`);
next();
};
// 使用中间件
app.use(logRequestTime);
app.get('/', (req, res) => {
res.send('Hello World!');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
在上述代码中,logRequestTime
函数就是定义的中间件,它获取当前时间并打印到控制台,然后通过next()
将控制权交给下一个中间件或路由处理程序。app.use(logRequestTime)
将该中间件应用到整个应用。