瀏覽器 CORS

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

  • 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)
複製代碼

性能優化方法

Access-Control-Max-Age

相關文章
相關標籤/搜索