0


axios跨域请求设置并携带Cookies

axios跨域请求设置Cookies

书接上回:《axios转发/oauth/authorize未设置cookies问题》
上回实现了axios 在client域名下情趣oauth域名并使response返回Set-Cookies的header
在这里插入图片描述
但是,接下来在域名oauth.szile.com域名下请求接口时,请求没有携带设置的Cookie,这是问什么? 难道是没有设置成功?
在这里插入图片描述
查看Application下Cookie,确实是没有设置成功。
在这里插入图片描述
经过搜索查找说 axios的请求必须配置axios.defaults.withCredentials = true,并且Response的Header需要有Access-Control-Allow-Credentials: true。

配置axios

// 创建axios实例const service = axios.create({baseURL: process.env.VUE_APP_BASE_API,// api的base_urltimeout:0,// 请求超时时间withCredentials:true})// 或者// axios.defaults.withCredentials = true;

Response header中写返回了
在这里插入图片描述
但却报跨域错误
在这里插入图片描述
在这里插入图片描述
从console信息「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’.」时说当请求是携带凭据模式(即Access-Control-Allow-Credentials: true、携带Cookie)时,Response的header “Access-Control-Allow-Origin” 的值不能是“” 通配符。

经过需改配置

@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled =true)publicclassWebSecurityConfigurationextendsWebSecurityConfigurerAdapterimplementsInitializingBean{// *** 此处省略 *** @Overrideprotectedvoidconfigure(HttpSecurity http)throwsException{
        http.cors().configurationSource(httpServletRequest ->{finalCorsConfiguration corsConfiguration =newCorsConfiguration();
            corsConfiguration.setAllowedOrigins(List.of("*"));
            corsConfiguration.setAllowedHeaders(List.of("*"));
            corsConfiguration.setAllowCredentials(true);return corsConfiguration;});// *** 此处省略 *** }}

成功的设置Cookie
在这里插入图片描述
在这里插入图片描述

总结

  1. 跨域请求是携带Cookie ,需要配置axios.defaults.withCredentials = true;
  2. 响应需要携带响应头 Access-Control-Allow-Credentials: true;
  3. 响应头 Access-Control-Allow-Origin 不能是通配符“*” ,并且需要和请求头Origin 的值一致。
标签: spring vue.js

本文转载自: https://blog.csdn.net/weixin_39515823/article/details/127715530
版权归原作者 超人@不会飞 所有, 如有侵权,请联系我们删除。

“axios跨域请求设置并携带Cookies”的评论:

还没有评论