服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Springboot处理配置CORS跨域请求时碰到的坑

Springboot处理配置CORS跨域请求时碰到的坑

2022-01-17 12:06没头脑遇到不高兴 Java教程

本篇文章介绍了我在开发过程中遇到的一个问题,以及解决该问题的过程及思路,通读本篇对大家的学习或工作具有一定的价值,需要的朋友可以参考下

最近开发过程中遇到了一个问题,之前没有太注意,这里记录一下。我用的SpringBoot版本是2.0.5,在跟前端联调的时候,有个请求因为用户权限不够就被拦截器拦截了,拦截器拦截之后打印日志然后response了一个错误返回了,但是前端Vue.js一直报如下跨域的错误,但是我是配置了跨域的。

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我的拦截器中代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private void writeResponse(HttpServletResponse response,
        ResponseResult<?> respResult, JSONObject reqParams) {
    PrintWriter writer = null;
    try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        writer = response.getWriter();
        writer.write(JSON.toJSONString(respResult));
        writer.flush();
    } catch (Exception e) {
        log.error("拦截器响应异常,respJson:"+reqParams, e);
    } finally{
        if(writer != null){
            writer.close();
        }
    }
}

我的拦截器是通过实现WebMvcConfigurer接口,然后重新其addCorsMappings(CorsRegistry registry)方法添加跨域设置的,具体如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
 
    @Bean
    public UserCenterInterceptor userTokenInterceptor() {
        return new UserCenterInterceptor();
    }
   
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedMethods("GET","POST","OPTIONS")
        .allowedOrigins("你要设置的域名")
        .allowedHeaders("*")
        .allowCredentials(true);
        WebMvcConfigurer.super.addCorsMappings(registry);
    }
}

原因是请求经过的先后顺序问题,请求会先进入到自定义拦截器中,而不是进入Mapping映射中,所以返回的头信息中并没有配置的跨域信息,浏览器就会报跨域异常。

正确的设置跨域的方式是通过CorsFilter过滤器,具体代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Configuration
public class CorsConfig {
 
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }
 
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

完美解决了坑,很开森,哈哈哈!!!继续行走在踩坑的路上。。。。。。

Springboot处理配置CORS跨域请求时碰到的坑

到此这篇关于Springboot处理配置CORS跨域请求时碰到的坑的文章就介绍到这了,更多相关Springboot CORS跨域请求内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/u012988901/article/details/97395556

延伸 · 阅读

精彩推荐