Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't koa-router be put before koa-cors?

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?

like image 767
guo Avatar asked Mar 08 '23 18:03

guo


2 Answers

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.

like image 156
Li Chunlin Avatar answered Mar 16 '23 15:03

Li Chunlin


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.

like image 36
amilete Avatar answered Mar 16 '23 16:03

amilete