場景及問題描述:
項目爲前後端分離,後端項目使用Maven多模塊項目+SpringBoot,前端使用 VUE。
後端在登錄接口保存當前用戶信息到session,前端請求後端接口,後端攔截器無法從session中獲取當前登錄的用戶,前端出現以下跨域報錯
錯誤信息:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
問題分析:
轉自:https://www.jianshu.com/p/c115e4a24977
當請求的憑據模式爲include時,相應中的Access-Control-Allow-Origin標頭的值不能是通配符 "*"
如在請求定義中設置withCredentials標誌,則會在請求中傳遞cookie等。
如果服務器返回任何set-cookie響應頭, 那麼必須返回Access-Control-Allow-Credentials: true, 否則將不會在客戶端上創建 cookie
如果你這樣設置,你需要同時指定了確切的Access-Control-Allow-Origin響應頭,因爲Access-Control-Allow-Origin: 不具有憑證兼容
--->當請求中攜帶cookie時, Access-Control-Allow-Origin必須要有確切的指定, 不能是通配符(*), 而withCredentials是跨域安全策略的一個東西
解決方案:
1、前端vue設置全局參數withCredentials : true
2、後端相關Controller添加跨域註解@CrossOrigin
3、後端新建CorsConfig類,繼承WebMvcConfigurerAdapter,並重寫addCorsMappings方法
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry) {
//設置允許跨域的路徑
registry.addMapping("/**")
//設置允許跨域請求的域名
.allowedOrigins("*")
//這裏:是否允許證書 不再默認開啓
.allowCredentials(true)
//設置允許的方法
.allowedMethods("*")
//跨域允許時間
.maxAge(3600);
}
}
相關問題博客:vuejs前後端分離,session問題