在使用Vue和SpringBoot做前后端分离项目时,会出现以下问题:

  1. 前端直接请求数据会出现跨域访问限制的问题。
  2. 如果登录时还需要图片验证码验证,首先需要请求获取验证码的接口,然后将验证码存入session中并返回给前端,登录时拿用户输入的验证码和session中保存的验证码比较,这时会发现session中获取不到之前存入的验证码,这是sessionId改变导致的。

1.后台数据请求部分处理

后台使用SpringBoot,需要配置过滤器来处理跨域请求。

1.1 编写过滤器配置类 FilterConfig

在过滤器中配置Access-Control-Allow-Origin使后台支持跨域请求。

设置Access-Control-Allow-Credentials属性为true使sessionId保持不变。


import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.*;
@Component
public class FilterConfig implements HandlerInterceptor{
	
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }
 
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2)
            throws Exception {
    }
 
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
 
    	response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");//Origin, X-Requested-With, Content-Type, Accept,Access-Token
        return true;
    }
}

关键是这两句 

response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));//支持跨域请求

response.setHeader("Access-Control-Allow-Credentials", "true");//是否支持cookie跨域

注意:当Access-Control-Allow-Credentials设置为ture时,Access-Control-Allow-Origin不能设置为*

1.2编写SpringMVCConfig类使用FilterConfig中的配置


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SuppressWarnings("deprecation")
@SpringBootConfiguration
public class SpringMVCConfig extends WebMvcConfigurerAdapter{
	@Autowired
	private FilterConfig filterConfig;
	
	public void addInterceptors(InterceptorRegistry registry){
		registry.addInterceptor(filterConfig).addPathPatterns("/**");
	}
}

2.前端使用 axios请求数据

axios默认是发送请求的时候不会带上cookie的,需要通过设置withCredentials: true来解决 

axios.defaults.withCredentials = true

 

Logo

前往低代码交流专区

更多推荐