nitro icon indicating copy to clipboard operation
nitro copied to clipboard

cors support for route rules

Open pi0 opened this issue 2 years ago • 3 comments

Context: https://github.com/nuxt/framework/issues/4009

Proposal:

routes: {
  '/public': { cors: true }
}

We probably need an h3 utility for this as well: https://github.com/unjs/h3/issues/82

pi0 avatar Apr 12 '22 17:04 pi0

@pi0 What about enabling cors in general? I created another thread under Nuxt and the suggested approach was to create a Nitro plugin. I could however not get it to work the same way it works for express.

This is the code that works with an express server (notice the origin value set to localhost:3100). The client can access the end points just fine:

app.use(
  cors({
    origin: 'http://localhost:3100',
    credentials: true,
  })
)
app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3100')
  res.header('Access-Control-Allow-Credentials', true)
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
  res.header(
    'Access-Control-Allow-Headers',
    'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json'
  )
  next()
})

The corresponding Nitro plugin does not work. Maybe I messed up somewhere? The client app compains that the origin is set to '*' even though I set it to localhost:

import cors from 'cors'

export default defineNitroPlugin(({ h3App }) => {
  h3App.use(
    cors({
      origin: 'http://localhost:3100',
      credentials: true,
    })
  )
  h3App.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:3100')
    res.header('Access-Control-Allow-Credentials', true)
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    res.header(
      'Access-Control-Allow-Headers',
      'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json'
    )
    next()
  })
})

Any help would be appreciated.

ahku avatar Apr 20 '22 20:04 ahku

We can globally enable it with routing rules too:

routes: {
  '/**': { cors: true }
}

pi0 avatar Apr 20 '22 20:04 pi0

Hey, is there any development on this? I am also struggling with cors and the options method.

harryyaprakov avatar May 27 '22 11:05 harryyaprakov