问题描述
springboot后端:设置验证码并存入session用于验证,前端使用接口发现无法设置session,且获取session同时为空指针异常
vue 前端:每发送一次请求生成一个新sessionid与第一次会话sessionID不一致。
跨域原因
通俗来说就是你的网站没有遵守同源策略,被javascript的安全策略给拦截了请求
那么什么又是同源策略呢?
同源指的是协议、域名、端口 都要保持一致
http://www.123.com:8080/index.html (http协议,www.123.com 域名、8080 端口 ,只要这三个有一项不一样的都是跨域,这里不一一举例子)
http://www.123.com:8080/matsh.html(不跨域)
http://www.123.com:8081/matsh.html(端口不一样,跨域)
注意:localhost 和127.0.0.1 虽然都指向本机,但也属于跨域。
所以如何解决SpringBoot+Vue中出现的跨域问题?
后端
通过自定义MVC配置放行跨域请求,允许访问。
package com.juran.xdd.security.webmvc;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 作者: Juran on 2021/12/16 14:18
* 作者博客:iit.la
*/
@Configuration
public class CorsFilter implements WebMvcConfigurer {
//解决前后端分离跨域问题
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")//设置允许跨域的路径
.allowedOrigins("*")//设置允许跨域请求的域名
.allowCredentials(true)//是否允许证书 不再默认开启
.allowedMethods("GET", "POST", "PUT", "DELETE")//设置允许的方法
.maxAge(3600);//跨域允许时间
}
}
前端
在前后端分离架构中,使用vue、angular 等发送ajax存在跨域请求没有携带请求凭证(cookie、HTTP认证及客户端SSL证明)造成request.getSession()获取的是不同的sessionId。要想在跨域的情况下带上Cookie。必须设置属性
使用vue.resource发送请求时配置如下:main.js中
Vue.http.options.xhr = { withCredentials: true }
使用vue.axios发送请求时配置如下:
axios.defaults.withCredentials = true;
jquery请求带上 xhrFields: {withCredentials: true}, crossDomain: true;
$.ajax({
type: "post",
url: "",
xhrFields: {withCredentials: true},
crossDomain: true,
data: {username:$("#username").val()},
dataType: "json",
success: function(data){ }
});
这样才能让后端获取到的Session与前端的sessionid一致。
同时还有一种情况如果你在封装axios情况下 也需要设置该属性,直接放入main.js文件中无法生效,需要将该参数放入你所封装的文件之中,亲测。该问题困扰我半天。
当然解决问题的办法不知一种。还有注入Bean、Filter等方式。