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

2022-07-21,,,,

最近开发过程中遇到了一个问题,之前没有太注意,这里记录一下。我用的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.

我的拦截器中代码如下:

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)方法添加跨域设置的,具体如下所示:

@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过滤器,具体代码如下:

@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跨域请求时碰到的坑.doc》

下载本文的Word格式文档,以方便收藏与打印。