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-
withCorsis 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.
isOriginAlloweda function to validate theOriginheader of the requestaccessControlAllowHeaderscontrol theAccess-Control-Allow-Headersheader. Defaults to['origin', 'content-type', 'accept', 'authorization']accessControlAllowMethodscontrol theAccess-Control-Allow-Methodsheader. Defaults to['GET', 'OPTIONS', 'HEAD']accessControlMaxAgecontrol theAccess-Control-Max-Ageheader. Defaults to3600seconds.accessControlAllowCredentialscontrol theAccess-Control-Allow-Credentialsheader. Defaults tofalse.accessControlExposeHeaderscontrol theAccess-Control-Expose-Headersheader. Defaults to[].
-
corsis 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
WithCorsOptionsThis function is used by
withCorswhere theaccessControlAllowOriginis set to theOriginheader 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.