最近在做java项目,用到拦截器Interceptor,由于项目是前后端分离,所以存在跨域问题。
解决java 跨域问题有很多,什么ajax jsonp方式,这就不适用我这个了,我这里主要介绍后台代码,
1、interceptor添加
//支持跨域请求
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
// httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,X-Nideshop-Token,X-URL-PATH");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
httpServletResponse.setHeader("Content-Type", "application/json");
主要是这句httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");解决跨域
2、mvcConfig public class MvcConfigextends WebMvcConfigurationSupport
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")// 允许跨域访问的路径
.allowedOrigins("*")// 允许跨域访问的源
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")// 允许请求方法
.maxAge(168000)// 预检间隔时间
.allowedHeaders("*")// 允许头部设置
.allowCredentials(true); // 是否发送cookie
}
这样也行
但是interceptor和addCorsMappings一起的话addCorsMappings机会失效,应该是顺序问题,interceptor覆盖了
网友评论