springboot java 跨域 问题处理

2022/4/14 1:12:29

本文主要是介绍springboot java 跨域 问题处理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

问题

很多时候在控制器中设置了跨域注解 没有用!

直接在拦截器中配置

方式一

@Component
public class TokenInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入LoginInterceptor拦截器---------------------------------------");


        //添加跨域CORS
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
}
}

方式二

利用 CorsConfiguration 类解决

  /**
     * 配置跨域
     * @return
     */
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // cookie跨域
        config.setAllowCredentials(Boolean.TRUE);
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        // 配置前端js允许访问的自定义响应头
        config.addExposedHeader("token");
        config.addExposedHeader("username");
        config.addExposedHeader("content-disposition");
        config.addExposedHeader("filename");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }



·



这篇关于springboot java 跨域 问题处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程