本文共 1930 字,大约阅读时间需要 6 分钟。
在Spring Boot项目中,解决跨域问题是一个常见的需求。通过重写WebMvcConfigurer的addCORSMapping方法,可以有效地处理跨域问题。然而,有时候在实际操作中可能会遇到一些特定的配置问题。
在前面的博客中,我们提到可以通过重写addCORSMapping方法来解决跨域问题。然而,在实际应用中可能会遇到以下错误提示:
When allowCredentials is true, allowedOrigins cannot contain th
这条错误提示的意思是,当允许传输敏感信息(allowCredentials为true)时,allowedOrigins数组中不能包含某些特定值。这通常是因为浏览器对同一域名下的跨域请求有限制。
如果你在项目中使用了静态资源映射,并通过编写配置类实现了WebMvcConfigurer接口并重写了addResourceHandlers方法来配置静态资源路径,但仍然出现跨域问题,可能是因为静态资源和API的跨域配置不一致。这种情况下,你需要分别处理静态资源的CORS配置和API的CORS配置。
WebMvcConfigurer中手动配置CORS:@Overridepublic void addCORSMapping() { super.addCORSMapping(new CorsConfigSource() { @Override publicCorsConfiguration getCorsConfiguration(String name) throwsNoSuchElementException { return newCorsConfiguration() .setAllowedOrigins(Arrays.asList("http://localhost:8080", "http://yourdomain.com")) .setAllowedMethods(Arrays.asList("GET", "POST", "PUT")) .setAllowCredentials(true); } });} CORSFilter来处理CORS问题: 在Spring Boot中,可以通过添加CORSFilter来实现CORS配置。这种方法相比直接重写addCORSMapping方法更灵活。import org.springframework.boot.web.servlet.filter.CorsFilter;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class WebConfig { @Bean public CorsFilter corsFilter() { return new CorsFilter(); }} application.properties中手动配置: 在application.properties文件中,可以添加以下配置:spring.http.cors.enabled=truespring.http.cors.allowedOrigins=http://localhost:8080,http://yourdomain.comspring.http.cors.allowCredentials=true
allowedOrigins的配置:
http://localhost:8080和http://localhost:8081。allowCredentials的配置:
allowCredentials=true。allowCredentials,而是根据具体需求进行配置。通过以上方法,你可以根据项目需求灵活配置跨域策略。如果仍然遇到问题,可以参考Spring Boot官方文档或相关技术博客,获取更详细的解决方案。
转载地址:http://yjvfk.baihongyu.com/