项目场景:
最近带着做了一个信用贷项目,因为之前系统搭建项目比较少,加上第一次做前后端真正分离的项目,记录下碰到的一个跨域问题问题描述:
前端出现跨域问题:浏览器对同源策略的校验,解决方案:@Override
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//支持跨域
registry.addMapping("/**").allowedOrigins("*").allowedMethods("POST","GET").allowedHeaders("*");
}
public static List<String> pathPatterns = new ArrayList<>();
@Override
public void addInterceptors(InterceptorRegistry registry) {
pathPatterns.add("/channel/index");
registry.addInterceptor(new JwtTokenInterceptor()).addPathPatterns("/**").excludePathPatterns(pathPatterns);
}
}z
原因分析:
使用上述方案只解决了/channel/index的跨域问题,原因是jwt拦截器会先于跨域mapping先执行,导致返回头中未加入允许前端跨域的头。
解决方案:
配置过滤器来解决跨域问题,过滤器先于拦截器执行
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/** 跨域过滤器
* @author hex
* @date 2020-12-2 17:43
* @return
*/
@Component
@WebFilter(urlPatterns = "/**",filterName = "crosFilter")
public class CrosFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse rsp = (HttpServletResponse) resp;
rsp.setHeader("Access-Control-Allow-Origin","*");
rsp.setHeader("Access-Control-Allow-Methods","POST,GET");
rsp.setHeader("Access-Control-Max-Age","3600");
rsp.setHeader("Access-Control-Allow-Headers","*");
filterChain.doFilter(req,resp);
}
@Override
public void destroy() {
}
}