本人新手自作springboot项目,按照网上主流方法解决跨域问题,没问题,但是打成war包部署到公司的tomcat服务器时会产生跨域,百度尝试多种springboot解决跨域方法无果,自创方法,可能只适合于本人,不喜勿喷,可以纠错
起初是这样的
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
String token = request.getHeader("x-access-token");
if (StringUtil.isEmpty(token)) {
JSONObject res = new JSONObject();
res.put("data", new ArrayList<>());
res.put("message", "请登录后访问");
res.put("code", 1001);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
out = response.getWriter();
out.append(res.toString());
return false;
}
解决跨域问题
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 允许任何头
corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
return new CorsFilter(source);
}
}
此方法对我本地的服务器有效,上传公司服务器无效,具体原因不详
换另一种
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.maxAge(3600)
.allowCredentials(true);
}
}
此方法可解决跨域但是,提示Origins预请求拦截,因为预请求没有token值,所以获取token直接抛出空指针异常
最终解决方法:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
//获取请求方式
String method = request.getMethod();
//如果为"OPTIONS"直接返回true(不拦截)
if(!method.equals("OPTIONS")){
logger.info("请求路径:"+request.getRequestURI());
String token = request.getHeader("x-access-token");
if (StringUtil.isEmpty(token)) {
JSONObject res = new JSONObject();
res.put("data", new ArrayList<>());
res.put("message", "请登录后访问");
res.put("code", 1001);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
out = response.getWriter();
out.append(res.toString());
return false;
}
}
新增一种方法:
@Configuration
public class MyConfiguration {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
跨域也可能跟tomcat有关,第二种方法新增class 并将tomcat还原默认配置即可解决跨域