location /joinus {
# 允許跨域請求的“域”,有些請求不允許*
add_header 'Access-Control-Allow-Origin' $http_origin always;# 不標注always 發生500 400錯誤時候會導致跨域失效
# 允許客戶端提交Cookie
add_header 'Access-Control-Allow-Credentials' 'true';
# 允許客戶端的請求方法
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
# 允許客戶端提交的的請求頭
add_header 'Access-Control-Allow-Headers' $http_access_control_request_headers;
# 允許客戶端訪問的響應頭
add_header 'Access-Control-Expose-Headers' 'Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma, satoken';
# 處理預檢請求
if ($request_method = 'OPTIONS') {
# 預檢請求緩存時間
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
# 允許客戶端提交的的請求頭
add_header 'Access-Control-Allow-Headers' $http_access_control_request_headers;
# 允許客戶端訪問的響應頭,根據自己實際需要添加,比如我用到了satoken就加入了對應的header
add_header 'Access-Control-Expose-Headers' 'Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma, satoken';
add_header 'Content-Length' 0;
add_header 'Access-Control-Allow-Credentials' 'true';
return 204;
}
#關閉重定向,如果出現POST變GET的情況,請務必加上此句。
proxy_redirect off;
proxy_pass http://127.0.0.1:8099;
}
尤其注意if語句,如果你在if語句里直接return,if外面的add_header會失效,這樣導致雖然瀏覽器的OPTIONS請求正常,但是帶上token之類的header,請求就會直接CORS錯誤。不少其他網絡資料都沒有提到這點。
經過測試解決springboot和vue之間跨域通信的問題。
前端通過nginx解決跨域也可以,這樣會更簡單一些。