Ask Your Question
1

What is the process for configuring CORS preflight in AdonisJS v5.9.0?

asked 2023-07-18 02:31:03 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-18 02:53:02 +0000

lakamha gravatar image

To configure CORS preflight in AdonisJS v5.9.0, follow these steps:

  1. Install the @adonisjs/cors package using npm:
npm i @adonisjs/cors@latest
  1. Register the middleware in the start/kernel.ts file:
import corsMiddleware from '@adonisjs/cors'

...

const serverMiddleware = [
  ...
  /*
  |--------------------------------------------------------------------------
  | Cross-Origin Resource Sharing (CORS)
  |--------------------------------------------------------------------------
  |
  | Enables CORS middleware which will handle CORS for you.
  | This is required when running on a different domain than the API.
  |
  */
  corsMiddleware({ origin: '*' }),
]
  1. Configure the options for the middleware by passing it an options object. In this example, { origin: '*' } means that any origin is allowed. You can also restrict allowed origins to specific domains.
import corsMiddleware from '@adonisjs/cors'

...

const serverMiddleware = [
  ...
  corsMiddleware({
    origin: (requestOrigin, callback) => {
      if (requestOrigin && requestOrigin.startsWith('https://example.com')) {
        return callback(null, true)
      }

      return callback(new Error('Not allowed by CORS'))
    },
    methods: ['GET', 'POST'],
    headers: true,
    exposedHeaders: [],
    credentials: true,
    maxAge: 90,
  }),
]
  1. Test your API by sending a CORS request from a different domain:
fetch('https://your-api-domain.com', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Request-Headers': 'X-Custom-Header',
    'Access-Control-Request-Method': 'POST',
  },
  mode: 'cors',
})
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-18 02:31:03 +0000

Seen: 10 times

Last updated: Jul 18 '23