location /han {
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,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
root html;
index index.html index.htm;
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5;
}
一、Access-Control-Allow-Origin,這裏使用變量 $http_origin取得當前來源域,你們說用「*」表明容許全部,我實際使用並不成功,緣由未知;html
二、Access-Control-Allow-Credentials,爲 true 的時候指請求時可帶上Cookie,本身按狀況配置吧;前端
三、Access-Control-Allow-Methods,OPTIONS必定要有的,另一般也就GET和POST,若是你有其它的也可加進去;web
四、Access-Control-Allow-Headers,這個要注意,裏面必定要包含自定義的http頭字段(就是說前端請求接口時,若是在http頭裏加了自定義的字段,這裏配置必定要寫上相應的字段),從上面可看到我寫的比較長,我在網上搜索一些經常使用的寫進去了,裏面有「web-token」和「app-token」,這個是我項目裏前端請求時設置的,因此我在這裏要寫上;後端
五、Access-Control-Expose-Headers,可不設置,看網上大體意思是默認只能獲返回頭的6個基本字段,要獲取其它額外的,先在這設置才能獲取它;跨域
六、語句「 if ($request_method = 'OPTIONS') { 」,由於瀏覽器判斷是否容許跨域時會先日後端發一個 options 請求,而後根據返回的結果判斷是否容許跨域請求,因此這裏單獨判斷這個請求,而後直接返回;瀏覽器