cors

NPM Version NPM Downloads Build Status Test Coverage

CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.CORS是一个node.js包,用于提供Connect/Express中间件,可用于启用具有各种选项的CORS

Follow me (@troygoode) on Twitter!

Installation安装

This is a Node.js module available through the npm registry. 这是一个Node.js模块,可通过npm注册表获得。Installation is done using the npm install command:使用npm install命令完成安装:

$ npm install cors

Usage用法

Simple Usage (Enable All CORS Requests)简单使用(启用所有CORS请求)

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Enable CORS for a Single Route为单个路由启用CORS

var express = require('express')
var cors = require('cors')
var app = express()

app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Configuring CORS配置CORS

var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for only example.com.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Configuring CORS w/ Dynamic Origin配置带动态来源的CORS

This module supports validating the origin dynamically using a function provided to the origin option. 此模块支持使用origin选项提供的函数动态验证来源。This function will be passed a string that is the origin (or undefined if the request has no origin), and a callback with the signature callback(error, origin).此函数将被传递一个作为来源的字符串(如果请求没有来源,则为undefined),以及一个带有签名callback(error, origin)的回调。

The origin argument to the callback can be any value allowed for the origin option of the middleware, except a function. 回调的origin参数可以是中间件的origin选项允许的任何值,函数除外。See the configuration options section for more information on all the possible value types.有关所有可能的值类型的更多信息,请参阅配置选项部分。

This function is designed to allow the dynamic loading of allowed origin(s) from a backing datasource, like a database.此函数旨在允许从备份数据源(如数据库)动态加载允许的源。

var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: function (origin, callback) {
    // db.loadOrigins is an example call to load
    // a list of origins from a backing database
    db.loadOrigins(function (error, origins) {
      callback(error, origins)
    })
  }
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for an allowed domain.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Enabling CORS Pre-Flight启用飞行前CORS

Certain CORS requests are considered 'complex' and require an initial OPTIONS request (called the "pre-flight request"). 某些CORS请求被视为“复杂”,需要初始OPTIONS请求(称为“飞行前请求”)。An example of a 'complex' CORS request is one that uses an HTTP verb other than GET/HEAD/POST (such as DELETE) or that uses custom headers. “复杂”CORS请求的一个示例是使用GET/HEAD/POST以外的HTTP谓词(例如DELETE)或使用自定义头的请求。To enable pre-flighting, you must add a new OPTIONS handler for the route you want to support:要启用预飞行,必须为要支持的路线添加新的选项处理程序:

var express = require('express')
var cors = require('cors')
var app = express()

app.options('/products/:id', cors()) // enable pre-flight request for DELETE request
app.del('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

You can also enable pre-flight across-the-board like so:您还可以像这样启用跨板预飞行功能:

app.options('*', cors()) // include before other routes

NOTE: When using this middleware as an application level middleware (for example, app.use(cors())), pre-flight requests are already handled for all routes.注意:当将此中间件用作应用程序级中间件(例如,app.use(cors())时),所有航线的飞行前请求都已得到处理。

Configuring CORS Asynchronously异步配置CORS

var express = require('express')
var cors = require('cors')
var app = express()

var allowlist = ['http://example1.com', 'http://example2.com']
var corsOptionsDelegate = function (req, callback) {
  var corsOptions;
  if (allowlist.indexOf(req.header('Origin')) !== -1) {
    corsOptions = { origin: true } // 在CORS响应中反映(启用)请求的来源
  } else {
    corsOptions = { origin: false } // disable CORS for this request针对此请求禁用CORS
  }
  callback(null, corsOptions) // 回调需要两个参数:error和options
}

app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for an allowed domain.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Configuration Options配置选项

The default configuration is the equivalent of:默认配置相当于:

{
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  "preflightContinue": false,
  "optionsSuccessStatus": 204
}

For details on the effect of each CORS header, read this article on HTML5 Rocks.有关每个CORS标题效果的详细信息,请阅读这篇关于HTML5的文章

Demo演示

A demo that illustrates CORS working (and not working) using React is available here: 此处提供了使用React演示CORS工作(和不工作)的演示:https://node-cors-client.netlify.com

Code for that demo can be found here:可在此处找到该演示的代码:

License许可证

MIT License

Author

Troy Goode (troygoode@gmail.com)