RingoJS

Module middleware/cors

Cross-site HTTP request headers

Implements the CORS (Cross-Origin Resource Sharing) protocol to enable cross-origin requests in browsers. Arbitrary HTTP clients may not comply to the protocol, so CORS cannot replace any server-side security mechanism.

Configuration options:

app.cors() accepts an object as parameter containing the following properties:

  • allowOrigin: configures the Access-Control-Allow-Origin header depending on the request's origin. Defaults to "*". The following options are supported:
    • String to set a specific origin; e.g. "https://example.com" or "*"
    • RegExp for dynamic origins; e.g. /https:\/\/www[12345]\.example\.com/
    • Array of strings to allow a set of different origins; e.g. ["https://example.com", "https://www.example.com"]
  • allowMethods: configures Access-Control-Allow-Methods; e.g. ["GET", "POST", "DELETE"]
  • allowHeaders: configures Access-Control-Allow-Headers; e.g. User-Agent, X-Custom-Header
  • exposeHeaders: configures Access-Control-Expose-Headers; e.g. Content-Length, X-Kuma-Revision
  • allowCredentials: if true, Access-Control-Allow-Credentials will be set to "true"
  • maxAge: configures Access-Control-Max-Age; use a negative value to disable preflight request caching
  • passthroughPreflights: if true, preflight requests will be forwarded to subsequent middlewares
  • optionsSuccessStatus: default HTTP status code for preflight responses

The default configuration is equivalent to:

app.cors({
  allowOrigin: "*",
  allowMethods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
  allowHeaders:  [],
  exposeHeaders: [],
  allowCredentials: false,
  maxAge: -1,
  passthroughPreflights: false,
  optionsSuccessStatus: 204
});

For a detailed explanation on what the different headers do, see MDN on CORS.

Example

app.configure("cors");
app.cors({
   allowOrigin: ["https://example.com", "https://www.example.com"],
   allowMethods: ["POST", "GET", "DELETE"],
   allowHeaders: ["X-PingOther"],
   exposeHeaders: []
   maxAge: 1728000,
   allowCredentials: true
})

Functions


middleware (next, app)

Parameters

null next
null app