Koa 框架搭建简单 HTTP 服务器示例

const Koa = require('koa');
const app = new Koa();

// logger 中间件
app.use(async (ctx, next) => {
  await next();
  const rt = ctx.response.get('X-Response-Time');
  console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});

// x-response-time 中间件
app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// response 中间件
app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

代码解释:

这段代码使用 Koa 框架建立了一个简单的 HTTP 服务器,并设置了三个中间件(middleware):

  1. **logger 中间件:**记录请求的方法、URL 以及响应时间。
  2. **x-response-time 中间件:**记录请求的开始时间,并在响应头中添加 X-Response-Time 字段来表示请求所花费的时间。
  3. **response 中间件:**返回 'Hello World' 作为响应体。

最后使用 app.listen(3000) 来监听 3000 端口,使服务器在该端口上运行。

Koa 框架搭建简单 HTTP 服务器示例

原文地址: https://www.cveoy.top/t/topic/micp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录