admin管理员组文章数量:1404358
I use Koa with Node.js 8.1.
Today I found that in my app.js, if I write in this order:
const Koa = require('koa')
var cors = require('koa-cors')
const app = new Koa()
app.use(cors(options))
app.use(router.routes())
the cors can work. I can verify the result via sending origin
header in Postman, and get
Access-Control-Allow-Origin
as response header.
However, if I write in this order:
const Koa = require('koa')
var cors = require('koa-cors')
const app = new Koa()
app.use(router.routes())
app.use(cors(options))
cors will not work correctly.
What's the problem here? AM I missing something?
I use Koa with Node.js 8.1.
Today I found that in my app.js, if I write in this order:
const Koa = require('koa')
var cors = require('koa-cors')
const app = new Koa()
app.use(cors(options))
app.use(router.routes())
the cors can work. I can verify the result via sending origin
header in Postman, and get
Access-Control-Allow-Origin
as response header.
However, if I write in this order:
const Koa = require('koa')
var cors = require('koa-cors')
const app = new Koa()
app.use(router.routes())
app.use(cors(options))
cors will not work correctly.
What's the problem here? AM I missing something?
Share Improve this question asked Jun 27, 2017 at 8:14 guoguo 10.2k11 gold badges50 silver badges84 bronze badges 1- If it works in any way similar to Express, the CORS headers need to be set before the router gets called to handle the request. – robertklep Commented Jun 27, 2017 at 8:20
2 Answers
Reset to default 4If you know what app.use()
does, you will understand what happened.
What the use()
function do is:
use(fn) {
this.middleware.push(fn);
return this;
}
So, the sequence of your code will affect the request handle process. It will route your request to your business code first and respond, cors will not be executed.
Commonly, the app.use(router.routes())
should be the last middleware.
The router routes will be modifying your request and operating on the response of it, so the cors headers need to be set prior to that, otherwise it won't work.
本文标签: javascriptWhy can39t koarouter be put before koacorsStack Overflow
版权声明:本文标题:javascript - Why can't koa-router be put before koa-cors? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744792103a2625350.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论