在Node.js中,您可以使用中间件来监控API响应时间。这里以Express框架为例,介绍如何使用中间件来监控API响应时间:
npm install express app.js的文件,并在其中引入Express模块:const express = require('express'); const app = express(); function responseTimeMiddleware(req, res, next) { const start = Date.now(); res.on('finish', () => { const duration = Date.now() - start; console.log(`${req.method} ${req.originalUrl} - ${duration}ms`); }); next(); } 在这个中间件函数中,我们记录了请求开始的时间,然后在响应结束时计算持续时间,并将其打印到控制台。
app.use()将中间件应用到所有路由:app.use(responseTimeMiddleware); app.get('/', (req, res) => { res.send('Hello World!'); }); app.get('/api/data', (req, res) => { setTimeout(() => { res.json({ message: 'This is a sample API response.' }); }, 1000); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); 现在,当您访问http://localhost:3000或http://localhost:3000/api/data时,控制台将显示API响应时间。
这只是一个简单的示例,您可以根据需要进行修改和扩展。例如,您可以将响应时间记录到日志文件中,或者使用第三方库(如morgan)来记录日志。