ShinGecko / neKo-Api

Api provided to support the innovative chat neKo
ISC License
0 stars 1 forks source link

Should this middleware be called at the end of the stack ? #2

Closed Shenrak closed 7 years ago

Shenrak commented 7 years ago

I have this middleware blocking my routes (can't set status, error is thrown)

function allowCrossDomain() {
  return function (ctx, next) {
    ctx.set('Access-Control-Allow-Origin', '*')
    ctx.set('Content-Type', 'text/html; charset=utf-8')
    ctx.set('Access-Control-Allow-Credentials', true)
    ctx.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    ctx.set('Access-Control-Allow-Headers', 'Content-Type,Authorization,Origin')
    next()
  }
}

Should this middleware be the last called ? Why so ?

justinrlle commented 7 years ago

Logically, it should be used at the begin of the stack. I think the problem is that your middleware doesn't return anything when it should return a promise.

Try with the following code:

function allowCrossDomain() {
  return function (ctx, next) {
    ctx.set('Access-Control-Allow-Origin', '*')
    ctx.set('Content-Type', 'text/html; charset=utf-8')
    ctx.set('Access-Control-Allow-Credentials', true)
    ctx.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    ctx.set('Access-Control-Allow-Headers', 'Content-Type,Authorization,Origin')
    return next() // the subtility is here! In the return!
  }
}

Also, I think this middleware is allowing Cross-Origin Resource Sharing? If so, there is already an official middleware for this.

justinrlle commented 7 years ago

Note that this solution is the same as marking the function async and you await on the next()

Shenrak commented 7 years ago

Your solution works fine ! This package has been created for Koa and we're using Koa2 so we'll keep going with the handmade middleware

justinrlle commented 7 years ago

In fact, by using koa-convert it won't be a problem, but let's keep it simple for now and stay with our little middleware.

So I'm closing this issue for now.

Shenrak commented 7 years ago

Actually I finally used koa2-cors