关于SpringBoot跨域问题

本人新手自作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还原默认配置即可解决跨域

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小可乐-我一直在

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值