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_url
  timeout: 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)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter implements InitializingBean {

    // *** 此处省略 *** 

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(httpServletRequest -> {
            final CorsConfiguration corsConfiguration = new CorsConfiguration();
            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 的值一致。
  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超人@不会飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值