• 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;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    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;
            });
            // *** 此处省略 *** 
        }
    }   
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

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

    总结

    1. 跨域请求是携带Cookie ,需要配置axios.defaults.withCredentials = true;
    2. 响应需要携带响应头 Access-Control-Allow-Credentials: true;
    3. 响应头 Access-Control-Allow-Origin 不能是通配符“*” ,并且需要和请求头Origin 的值一致。
  • 相关阅读:
    【计算机网络期末复习】选择题①1~50
    基于Cat混沌与高斯变异的改进灰狼优化算法-附代码
    PDF文件上传转成base64编码并支持预览
    科学计算器网站Desmos网站
    第十三届蓝桥杯省赛C/C++ B组
    技术人生的发展与问题思考
    SpringBoot-基本介绍与环境搭建
    回归预测模型:MATLAB神经网络回归模型
    《一个程序猿的生命周期》-《发展篇》- 44.再次进军内蒙市场(转型)
    JVM虚拟机浅谈(三)
  • 原文地址:https://blog.csdn.net/weixin_39515823/article/details/127715530