Google浏览器跨域不能设置cookie问题

在前后端分离的项目中Google浏览器中不能设置cookie,因为在Google浏览器80版本后增加了SameSite的cookie限制,默认为Lax模式不携带cookie和session。
network
解决这一问题的方法就是在正确配置springboot和vue的跨域配置的前提下做本地的域名映射,将本地的localhost地址映射成一个自定义的域名,不需要使用nginx做代理,直接通过访问域名进行联调测试。
(方案参考百度sso登录)
本地域名映射
需要在后端设置cookie时指定上域名,并且前端的接口调用也要使用此域名才能正常设置cookie。
因为cookie设置成功的自然而然session也就可以用了。
在这里插入图片描述
springboot跨域配置


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author: WangKangSheng
 * @create: 2020-11-22 15:31
 * 跨域配置
 */
@Configuration
public class CorsConfiguration implements WebMvcConfigurer {
    /**
     * Configure cross origin requests processing.
     * @param registry CorsRegistry
     */
    @Override public void addCorsMappings(CorsRegistry registry) {

        System.out.println("跨域配置");
        registry
                .addMapping("/**")  // 设置跨域的路径
                .allowedOrigins("*")    // 源头
                .allowedMethods("*")    // 方法
                .allowCredentials(true) // session和cookie
                .exposedHeaders("Access-Control-Allow-Origin",
                        "Access-Control-Allow-Credentials")
                .maxAge(3600);  // 请求的响应时间
    }
}

前端vue中axios的配置代码
在main.js中设置可携带cookie和session。

import axios from 'axios'
axios.defaults.withCredentials=true;

效果:
在这里插入图片描述
一切正常。(前面两个域名是线上的和本地的localhost测试域名)
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不想写代码~

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

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

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

打赏作者

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

抵扣说明:

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

余额充值