梗概

  • ctx中有request和response对象

示例

const Koa = require('koa');
const app = new Koa();
 
// 修改请求对象
app.use(async (ctx, next) => {
  // 修改请求URL
  ctx.request.url = '/new-url';
  
  // 添加自定义头部信息
  ctx.request.headers['X-Custom-Header'] = 'Custom Value';
  
  await next();
});
 
// 修改响应对象
app.use(async (ctx) => {
  // 修改响应状态码
  ctx.response.status = 201;
  
  // 添加自定义头部信息
  ctx.response.set('X-Custom-Header', 'Custom Value');
  
  // 发送自定义响应体
  ctx.body = 'Custom Response Body';
});
 
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});