cors_cors的安装与基本使用

安装

npm install 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')
})

允许单个路由的跨域请求

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')
})

跨域配置_白名单

var express = require('express')
var cors = require('cors')
var app = express()
 
var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}
 
app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
})
 
app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
  • 如果你不想阻止REST 工具或者服务器对服务器的请求, 添加一个!origin用来检查域名
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1 || !origin) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

允许预检请求跨域

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')
})
  • 也可以允许所有的预检请求
app.options('*', cors()) // include before other routes

配置参数

origin:
	Boolean: 根据req.header('Origin')的值, 将这个值设定为true以允许请求的域名跨域, 或者设置为false禁用该域名的跨域
	String: 设置为特定的域名并允许该域名的跨域请求, 例如将其设置为'http://example.com'会允许该域名的跨域请求
	RegExp: 如果设置的正则表达式匹配请求域名, 那么允许该域名跨域
	Array: 允许跨域的域名组成的数组
	Function: 第一个参数是请求的域名, 回调函数作为第二个参数
methods:
	配置访问域名所允许的方法, 应为逗号分隔的字符串或数组, 例如'GET,PUT,POST'或者['GET','PUT','POST']
allowedHeaders:
	配置访问控制允许标头CORS标头。应为逗号分隔的字符串(例如:“Content Type,Authorization”)或数组(例如:[“Content Type”,“Authorization”])。如果未指定,则默认为反映请求的访问控制请求标头中指定的标头。
exposedHeaders:
credentials:
maxAge:
preflightContinue:
optionsSuccessStatus:
 
  • cors的默认配置

    • {
        "origin": "*",
        "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
        "preflightContinue": false,
        "optionsSuccessStatus": 204
      }
      
posted @ 2023-10-03 23:07  Syinho  阅读(116)  评论(0编辑  收藏  举报