-1

My project base on koa,I want to intercept HTTP response,when the response's message is "no promission",then excute 'this.redirect()'.

user3387471
  • 113
  • 2
  • 5

1 Answers1

1

Your middleware (interceptor in my example) can access the response body after it yield next, so just place your logic after it yields.

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...');
});
danneu
  • 9,244
  • 3
  • 35
  • 63