如何制作基于koa的中间件,用于拦截HTTP响应?

时间:2015-08-05 09:28:57

标签: koa

我的项目基于koa,我想拦截HTTP响应,当响应的消息是"没有promission",然后执行' this.redirect()'

1 个答案:

答案 0 :(得分:1)

您的中间件(我的示例中为interceptor)可以在yield next之后访问响应正文,因此只需在逻辑生成后放置它。

var route = require('koa-route');
var app = require('koa')();

var interceptor = function*(next) {
  // wait for downstream middleware/handlers to execute 
  // so that we can inspect the response

  yield next; 

  // our handler has run and set the response body,
  // so now we can access it

  console.log('Response body:', this.body);

  if (this.body === 'no promission') {
    this.redirect('/somewhere');
  }
};

app.use(interceptor);

app.use(route.get('/', function*() {
  this.body = 'no promission';
}));

app.listen(3001, function() {
  console.log('Listening on 3001...');
});