Springboot處理配置CORS跨域請求時碰到的坑
最近開發(fā)過程中遇到了一個問題,之前沒有太注意,這里記錄一下。我用的SpringBoot版本是2.0.5,在跟前端聯(lián)調(diào)的時候,有個請求因為用戶權(quán)限不夠就被攔截器攔截了,攔截器攔截之后打印日志然后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(); } } }
我的攔截器是通過實現(xiàn)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); } }
原因是請求經(jīng)過的先后順序問題,請求會先進入到自定義攔截器中,而不是進入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); } }
完美解決了坑,很開森,哈哈哈?。?!繼續(xù)行走在踩坑的路上。。。。。。
到此這篇關于Springboot處理配置CORS跨域請求時碰到的坑的文章就介紹到這了,更多相關Springboot CORS跨域請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot整合mybatisplus和druid的示例詳解
這篇文章主要介紹了SpringBoot整合mybatisplus和druid的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-08-08