How do I set headers to all responses in Koa.js?
Asked Answered
S

1

34

In Express.js I used to have this kind of code:

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
  next();
});

How do I do the same thing with Koa.js? I need to preset these several http headers for each server response.

Snowberry answered 3/4, 2018 at 14:56 Comment(0)
S
84

Finaly I found how to do it.

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  ctx.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
  await next();
});
Snowberry answered 3/4, 2018 at 15:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.