在開發(fā)的時候,我們經(jīng)常會遇到跨域問題,我們通常的解決方案是使用CORS或是JSONP來解決,但是更常用的解決方案便是CORS了,因為JSONP只支持GET請求。關(guān)于CORS的相關(guān)知識,請移步阮一峰的跨域資源共享 CORS 詳解這篇文章。
如果瀏覽器控制臺出現(xiàn)跨域相關(guān)的報錯時,一般是后端沒有允許跨域,所以需要后端服務(wù)器在代碼層面設(shè)置下。當然有的時候后端并不想對代碼進行改動,這個時候我們也可以直接在代理層nginx這里進行一些相關(guān)配置
比如我們要允許/api/v1下的相關(guān)接口支持跨域,我們可以這樣編寫nginx配置
location ^~ /api/v1 {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type ';
add_header 'Access-Control-Allow-Credentials' 'true';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type ';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Max-Age' 1728000; # 20 天
add_header 'Content-Type' 'text/html charset=UTF-8';
add_header 'Content-Length' 0;
return 200;
}
# 這下面是要被代理的后端服務(wù)器,它們就不需要修改代碼來支持跨域了
proxy_pass http://127.0.0.1:8085;
proxy_set_header Host $host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 60;
proxy_read_timeout 60;
proxy_send_timeout 60;
}