javascript 如何在 Koa.js 中为所有响应设置标头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49633157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:40:36 来源:igfitidea点击:
How do I set headers to all responses in Koa.js?
提问by Gherman
In Express.js I used to have this kind of code:
在 Express.js 中,我曾经有过这样的代码:
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.
我如何用 Koa.js 做同样的事情?我需要为每个服务器响应预设这几个 http 标头。
回答by Gherman
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();
});

