Springboot+vue 前后端分离出现后端session的获取为null

Springboot+vue 前后端分离出现后端校验验证码时出现获取session中的值为null的情况。

最近在写前后端分离的项目时,使用到后端验证码的情况。一般是在前端先get请求获取后端图片,并且将生成的验证存储到session中,然后前端再post请求登陆时,将form表单中的验证码传递到后端,然后后端再取出session中的验证码进行比较验证,但是由于跨域问题,在最后一步验证时出现取出的session值为null。在看了几篇博文后得出以下结论:
参考博文
https://blog.csdn.net/simg_dragon/article/details/108338427
https://blog.csdn.net/qq_43751336/article/details/111145876
首先是后端部分:

package com.example.demo.common;

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

@Configuration
public class CrossConfig implements WebMvcConfigurer {
    
    
    @Override
    /*请求跨域*/
    public void addCorsMappings(CorsRegistry registry) {
    
    
        // 设置允许跨域的路由
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 再次加入前端Origin  localhost!=127.0.0.1
                .allowedOrigins("http://localhost")
                // 是否允许证书(cookies)
                .allowCredentials(true)
                // 设置允许的方法
                .allowedMethods("*")
                //允许请求头
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }
}

主要是2个地方
1:allowCredentials(true)设置带cookie
2:allowedOrigins这里就不能写成allowedOrigins("*")要改成前端Origin记住localhost!=127.0.0.1
然后就是前端部分:

在main.js中配置axios这行代码

axios.defaults.withCredentials = true;

这样就将session由于跨域而失效的问题解决啦!

猜你喜欢

转载自blog.csdn.net/qq_44874270/article/details/112678613