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!
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 corsvar 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')
})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')
})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')
})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')
})Certain CORS requests are considered 'complex' and require an initial 某些CORS请求被视为“复杂”,需要初始OPTIONS request (called the "pre-flight request"). 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 routesNOTE: 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())时),所有航线的飞行前请求都已得到处理。
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')
})originBoolean - origin to true to reflect the request origin, as defined by req.header('Origin'), or set it to false to disable CORS.origin设置为true以反映请求来源,如req.header('Origin')所定义,或将其设置为false以禁用CORS。String - origin to a specific origin. origin设置为特定来源。"http://example.com" only requests from "http://example.com" will be allowed."http://example.com",则仅来自的请求http://example.com将被允许。RegExp - origin to a regular expression pattern which will be used to test the request origin. origin设置为正则表达式模式,该模式将用于测试请求源。/example\.com$/ will reflect any request that is coming from an origin ending with "example.com"./example\.com$/将反映来自以“example.com”结尾的源站的任何请求。Array - origin to an array of valid origins. origin设置为有效来源的数组。String or a RegExp. String或RegExp。["http://example1.com", /\.example2\.com$/] will accept any request from "http://example1.com" or from a subdomain of "example2.com".["http://example1.com", /\.example2\.com$/]将接受来自http://example1.com或来自子域example2.com的任何请求。Function - origin to a function implementing some custom logic. origin设置为实现某些自定义逻辑的函数。callback(err, origin), where origin is a non-function value of the origin option) as the second.callback(err, origin)的形式调用,其中origin是origin选项的非函数值)作为第二个参数。methods['GET', 'PUT', 'POST']).'GET'、'PUT'、'POST')或数组(例如:['GET', 'PUT', 'POST'])。allowedHeaders['Content-Type', 'Authorization']). 'Content-Type,Authorization')或数组(例如:['Content-Type', 'Authorization']。exposedHeaders['Content-Range', 'X-Content-Range']). 'Content-Range,X-Content-Range')或数组(例如:['Content-Range', 'X-Content-Range']。credentialstrue to pass the header, otherwise it is omitted.true以传递标头,否则将忽略它。maxAgepreflightContinueoptionsSuccessStatusOPTIONS requests, since some legacy browsers (IE11, various SmartTVs) choke on 204.OPTIONS请求的状态代码,因为某些传统浏览器(IE11、各种SmartTV)会阻塞204。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的文章。
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:可在此处找到该演示的代码: