CORS (Cross-Origin Resource Sharing) 是一种机制,它使用额外的 HTTP 头来告诉浏览器 让运行在一个 origin (domain) 上的Web应用被准许访问来自不同源服务器上的指定的资源。
当一个资源从与该资源本身所在的服务器不同的域、协议或端口请求一个资源时,资源会发起一个跨域 HTTP 请求。
过程
浏览器比较Request Header和Response Header
Request Header -> Origin VS Response Header -> Access-Control-Allow-Origin
Request Header -> Cookie VS Response Header -> Access-Control-Allow-Credentials
Request Method VS Response Header -> Access-Control-Allow-Methods (默认有GET/POST/HEAD)
Request Header -> 其他头部项 VS Response Header -> Access-Control-Allow-Headers
预检请求
简单请求的过程:
client ----> server
server ----> client
非简单请求的过程
client ----> server (OPTION)
server ----> client
client ----> server
server ----> client
判断简单请求的标准
同时满足以下五点的请求为简单请求:
-
使用下列方法之一:GET / HEAD / POST
-
Fetch 规范定义了对 CORS 安全的首部字段集合,不得人为设置该集合之外的其他首部字段。该集合为:
Accept / Accept-Language / Content-Language / Content-Type (需要注意额外的限制)/ DPR / Downlink / Save-Data / Viewport-Width / Width
- Content-Type 的值仅限于下列三者之一:
text/plain
multipart/form-data
application/x-www-form-urlencoded
-
请求中的任意XMLHttpRequestUpload 对象均没有注册任何事件监听器;XMLHttpRequestUpload 对象可以使用 XMLHttpRequest.upload 属性访问。
-
请求中没有使用 ReadableStream 对象。
Nginx 中的跨域配置
conf 文件
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
...
}
Node.js server 中的跨域
npm cors包
npm install cors --D
var express = require('express');
var cors = require('cors');
var app = express();
var corsOptions = {
origin: 'http://localhost:3000',
optionsSuccessStatus: 200
}
app.use(cors(corsOptions));
自己实现cors中间件
// kuayu.js
var kuayu = function (req, res, next) {
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Max-Age', 3);
res.header('Access-Control-Allow-Headers', 'x-header');
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
next();
}
module.exports = kuayu;
var express = require('express');
var kuayu = require('./kuayu.js');
var app = express();
app.use(kuayu)