技术架构:
在实战项目中,经常需要记录下服务器的响应时间,也就是从服务器接收到HTTP请求,到最终返回给客户端之间所耗时长。在Koa应用中,利用中间件机制可以很方便的实现这一功能。代码如下所示:
01 const koa = require('koa');
02 const app = new koa();
03 app.use(async (ctx, next) => { // 记录服务器响应时间的中间件
04 let stime = new Date().getTime(); // 记录当前时间戳
05 await next(); // 事件控制权中转
06 let etime = new Date().getTime(); // 所有中间件执行完成后记录当前时间
07 ctx.response.type = 'text/html';
08 ctx.response.body = '<h1>Hello World</h1>';
09 console.log(`请求地址: ${ctx.path},响应时间:${etime - stime}ms`