1、服務端可控,添加響應頭
2、服務端不可控、通過Nginx反向代理
3、服務端不可控、通過Nginx反向代理添加響應頭
第一種方法、服務端可控時,可以在服務器端添加響應頭(前端+后端解決)
瀏覽器地址為http://127.0.0.1:5501/xx.html
請求地址為http://localhost:3000/test
前端代碼
function myFunction() { $.get("http://localhost:3000/test", function (data, status) { alert("數據: " + data + "\n狀態: " + status); }); };
后端代碼(node+express)
//設置跨域訪問 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "http://127.0.0.1:5501");//將http://127.0.0.1:5501改成*可以允許所有跨域
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
next(); });
總結:直接訪問,在服務器端設置跨域頭即可
第二種方法、服務端不可控、通過Nginx反向代理(前端+Nginx解決)
瀏覽器地址為http://127.0.0.1:5000(實際頁面應為http://127.0.0.1:5501/xx.html)
請求地址為http://127.0.0.1:5000/test
Nginx配置為
server{ listen 5000; server_name localhost;
location = / { proxy_pass http://localhost:5501/xx.html; } location /test { proxy_pass http://localhost:3000/test; } }
前端代碼
function myFunction() {
$.get("http://localhost:5000/test", function (data, status) { alert("數據: " + data + "\n狀態: " + status); }); };
總結:原始頁面與待請求數據都通過Nginx監聽反向代理,由於頁面端口與請求端口一致則無需跨域。(瀏覽器地址欄非原始頁面,原始頁面與待請求數據都需要被反向代理)
第三種方法、服務端不可控、通過Nginx為響應添加跨域頭(前端+Nginx解決)
瀏覽器地址為http://127.0.0.1:5501/xx.htm
請求地址為http://127.0.0.1:5000/test
Nginx配置為
server{
listen 5000;
server_name localhost;
location = / {
proxy_pass http://localhost:3000/;
}
location /test {
proxy_pass http://localhost:3000/test;
# 指定允許跨域的方法,*代表所有
add_header Access-Control-Allow-Methods *;
# 預檢命令的緩存,如果不緩存每次會發送兩次請求
add_header Access-Control-Max-Age 3600;
# 帶cookie請求需要加上這個字段,並設置為true
add_header Access-Control-Allow-Credentials true;
# 表示允許這個域跨域調用(客戶端發送請求的域名和端口)
# $http_origin動態獲取請求客戶端請求的域 不用*的原因是帶cookie的請求不支持*號
add_header Access-Control-Allow-Origin $http_origin;
# 表示請求頭的字段 動態獲取
add_header Access-Control-Allow-Headers
$http_access_control_request_headers;
# OPTIONS預檢命令,預檢命令通過時才發送請求
# 檢查請求的類型是不是預檢命令
if ($request_method = OPTIONS){
return 200;
}
}
}
前端代碼
function myFunction() { $.get("http://localhost:5000/test", function (data, status) { alert("數據: " + data + "\n狀態: " + status); }); };
總結:瀏覽器地址欄為原始頁面,待獲取數據通過反向代理,再應答時通過Nginx添加跨域頭。(只有請求需要代理)