CORS (Cross-Origin Resource Sharing) 是一種機制,它使用額外的 HTTP 頭來告訴瀏覽器 讓運行在一個 origin (domain) 上的Web應用被准許訪問來自不一樣源服務器上的指定的資源。express
當一個資源從與該資源自己所在的服務器不一樣的域、協議或端口請求一個資源時,資源會發起一個跨域 HTTP 請求。npm
瀏覽器比較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-Headersbash
簡單請求的過程:服務器
client ----> serverapp
server ----> clientcors
非簡單請求的過程
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
text/plain
multipart/form-data
application/x-www-form-urlencoded
請求中的任意XMLHttpRequestUpload 對象均沒有註冊任何事件監聽器;XMLHttpRequestUpload 對象能夠使用 XMLHttpRequest.upload 屬性訪問。
請求中沒有使用 ReadableStream 對象。
conf 文件
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
...
}
複製代碼
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));
複製代碼
// 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)
複製代碼