5

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?

guo
  • 9,674
  • 9
  • 41
  • 79
  • 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 Jun 27 '17 at 08:20

2 Answers2

4

If 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.

Li Chunlin
  • 517
  • 3
  • 14
  • Could you explain more about "t will route your request to your business code first and respond, cors will not be executed."? Are there any reproducible evidences showing that cors doesn't executed? – guo Jun 27 '17 at 11:47
  • @guo ` 'use strict'; const Koa = require('koa'); const app = new Koa(); const myCors = function(ctx, next) { console.log('cors do something...'); next(); } const myRouter = function(ctx, next) { console.log('business logic...'); ctx.body = "respond some data"; } app.use(myRouter); app.use(myCors); app.listen(3001); ` You can try this very simple instance and then exchange two middleware and retry. Suggest you to read [koa guide](https://github.com/koajs/koa/blob/master/docs/guide.md) to understand middleware – Li Chunlin Jun 27 '17 at 14:29
3

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.

amilete
  • 106
  • 3