const globalMiddleware = [
// ...
'Adonis/Middleware/Cors'
// ...
]
You are viewing the legacy version of AdonisJS. Visit https://adonisjs.com for newer docs. This version will receive security patches until the end of 2021.
Cross-Origin Resource Sharing(CORS) is a way to allow incoming HTTP requests from different domains. It is very common in AJAX applications where the browser will block all cross-domain requests if the server does not authorize them. Read more about CORS here.
AJAX Requests from different domains needs to be authorized before they perform desired actions. Browsers first make a preflight request with OPTIONS as the HTTP method to the server granting permission. The server can allow the request by returning 200 OK and specifying the domains to be allowed via Access-Control-Allow-Origin header.
AdonisJs ships with a CORS middleware to handle this flow for you via a configuration file.
For CORS rules to work properly make sure that Adonis/Middleware/Cors
is registered as a global middleware inside app/Http/kernel.js
file.
const globalMiddleware = [
// ...
'Adonis/Middleware/Cors'
// ...
]
You can manage the CORS rules by editing the config/cors.js
configuration file.
module.exports = {
origin: false,
methods: 'GET, PUT, POST',
headers: true,
exposeHeaders: false,
credentials: false,
maxAge: 90
}
Origin accepts multiple values.
To disallow all CORS requests, set it false
To allow the same origin requests, set it to true
.
You can define comma(,) separated origins.
Setting the value to a wildcard *, will allow all origins.
Finally, you can attach a callback and return one of the above values
origin: function (requestOrigin) {
return requestOrigin === 'foo'
}
Http methods/verbs to allow. Make sure it is a comma-separated value of one of the multiple methods.
As origin, headers also accept multiple values
To disable all headers set to false.
To allow all headers defined inside Access-Control-Request-Headers set it to true.
Allow a string of comma(,) separated custom headers. For example, Content-Type, Accepts.
Finally, a callback function.
headers: function (requestedHeaders) {
// ...
}
Comma separated headers to expose via Access-Control-Expose-Headers header.
Allow or disallow credentials exchanged by setting Access-Control-Allow-Credentials header to a boolean value.
Sets Access-Control-Allow-Max-Age header to defined value.