1、問題背景:前端調用線上后段時出現跨域問題!
解決方法nginx的location頭部增加配置:
add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,HEAD,PUT';
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true'
本地前端調用php接口時需在后端的 location字段都加配置。
2、當出現403跨域錯誤的時候 No 'Access-Control-Allow-Origin' header is present on the requested resource,需要給Nginx服務器配置響應的header參數:
解決方案:
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
}
3、Ajax跨域請求保證同一個session的問題
我們知道,根據瀏覽器的保護規則,跨域的時候我們創建的sessionId是不會被瀏覽器保存下來的,這樣,當我們在進行跨域訪問的時候,我們的sessionId就不會被保存下來,也就是說,每一次的請求,服務器就會以為是一個新的人,而不是同一個人,為了解決這樣的辦法,下面這種方法可以解決這種跨域的辦法。
我們自己構建一個攔截器,對需要跨域訪問的request頭部重寫:
add_header Access-Control-Allow-Origin "$http_origin";
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
add_header Access-Control-Allow-Headers "Origin, Accept, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token";
add_header Access-Control-Allow-Credentials "true";
原文鏈接:https://blog.csdn.net/weixin_42207486/java/article/details/82494638