跨域解決方案
web 領(lǐng)域開發(fā)中,經(jīng)常采用前后端分離模式。這種模式下,前端和后端分別是獨(dú)立的 web 應(yīng)用程序,例如:后端是 Java 程序,前端是 React 或 Vue 應(yīng)用。
各自獨(dú)立的 web app 在互相訪問時(shí),勢(shì)必存在跨域問題。解決跨域問題一般有兩種思路:
CORS
在后端服務(wù)器設(shè)置 HTTP 響應(yīng)頭,把你需要運(yùn)行訪問的域名加入加入 Access-Control-Allow-Origin 中。
jsonp
把后端根據(jù)請(qǐng)求,構(gòu)造json數(shù)據(jù),并返回,前端用 jsonp 跨域。
這兩種思路,本文不展開討論。
需要說明的是,nginx 根據(jù)第一種思路,也提供了一種解決跨域的解決方案。
舉例:www.helloworld.com 網(wǎng)站是由一個(gè)前端 app ,一個(gè)后端 app 組成的。前端端口號(hào)為 9000, 后端端口號(hào)為 8080。
前端和后端如果使用 http 進(jìn)行交互時(shí),請(qǐng)求會(huì)被拒絕,因?yàn)榇嬖诳缬騿栴}。來看看,nginx 是怎么解決的吧:
首先,在 enable-cors.conf 文件中設(shè)置 cors :
set $ACAO '*';
# set single origin
if ($http_origin ~* (www.helloworld.com)$) {
set $ACAO $http_origin;
}
if ($cors = "trueget") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'OPTIONS') {
set $cors "${cors}options";
}
if ($request_method = 'GET') {
set $cors "${cors}get";
}
if ($request_method = 'POST') {
set $cors "${cors}post";
}
接下來,在你的服務(wù)器中 include enable-cors.conf 來引入跨域配置:
# ----------------------------------------------------
# 此文件為項(xiàng)目 nginx 配置片段
# 可以直接在 nginx config 中 include(推薦)
# 或者 copy 到現(xiàn)有 nginx 中,自行配置
# www.helloworld.com 域名需配合 dns hosts 進(jìn)行配置
# 其中,api 開啟了 cors,需配合本目錄下另一份配置文件
# ----------------------------------------------------
upstream front_server{
server www.helloworld.com:9000;
}
upstream api_server{
server www.helloworld.com:8080;
}
server {
listen 80;
server_name www.helloworld.com;
location ~ ^/api/ {
include enable-cors.conf;
proxy_pass http://api_server;
rewrite "^/api/(.*)$" /$1 break;
}
location ~ ^/ {
proxy_pass http://front_server;
}
}