A middleware to configure CORS behavior on a per route or request basis
- From the NPM registry
npm install @p-j/eapi-middleware-cors
# or
yarn add @p-j/eapi-middleware-cors
-
withCors
is a Middleware Factory; it takes in the following options:export interface WithCorsOptions { isOriginAllowed?: Function accessControlAllowHeaders?: string[] accessControlAllowMethods?: string[] accessControlMaxAge?: number accessControlAllowCredentials?: boolean accessControlExposeHeaders?: string[] }
As noted above, none of the options are required.
isOriginAllowed
a function to validate theOrigin
header of the requestaccessControlAllowHeaders
control theAccess-Control-Allow-Headers
header. Defaults to['origin', 'content-type', 'accept', 'authorization']
accessControlAllowMethods
control theAccess-Control-Allow-Methods
header. Defaults to['GET', 'OPTIONS', 'HEAD']
accessControlMaxAge
control theAccess-Control-Max-Age
header. Defaults to3600
seconds.accessControlAllowCredentials
control theAccess-Control-Allow-Credentials
header. Defaults tofalse
.accessControlExposeHeaders
control theAccess-Control-Expose-Headers
header. Defaults to[]
.
-
cors
is a utility function that adds CORS headers to aResponse
; it takes in the following options:export interface CorsOptions extends WithCorsOptions { response: Response accessControlAllowOrigin?: string }
Note: it extends the
WithCorsOptions
This function is used by
withCors
where theaccessControlAllowOrigin
is set to theOrigin
header of the request.
If the requestHandler
given to withCors
or the response
given to cors
already contains Access-Control-* Headers, they will be overriden with whatever config is given.