Spring Boot与Angular的CORS配置问题排查求助
CORS策略异常排查求助
问题场景
- Angular应用运行在
localhost:4200,Spring Boot后端运行在localhost:8081,跨域请求时触发CORS错误,具体错误信息:
Access to XMLHttpRequest at 'http://localhost:8081/api/houses/1' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
- 房屋新增功能(POST请求)可正常运行,但更新房屋信息(PATCH请求)触发上述CORS问题,同源请求表现不一致
- 加载房屋列表页面时曾遇CORS问题,已通过Spring Boot后端添加Web配置解决,但更新房屋和加载房屋3D模型时仍报错,加载房屋图片则无异常
已尝试的解决方案
- 添加
WebMvcConfigurer配置类:
import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:4200") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .exposedHeaders("Access-Control-Allow-Origin") .allowCredentials(true); } }
- 在
application.properties中添加CORS配置:
spring.web.cors.allowed-methods=* spring.web.cors.allowed-headers=*
- 配置Angular代理(
proxy.conf.json):
{ "/api": { "target": "http://localhost:8081", "secure": false, "changeOrigin": true, "logLevel": "debug" }, "/uploads": { "target": "http://localhost:8081", "secure": false, "changeOrigin": true, "logLevel": "debug" } }
并通过命令ng serve --proxy-config proxy.conf.json启动Angular应用
4. 使用curl命令测试后端CORS,未触发问题,完整命令:
curl -X PATCH http://localhost:8081/api/houses/1 \ -H "Content-Type: application/json" \ -d '{"name": "Updated House", "location": "Updated Location"}'
- 尝试使用CORS Anywhere,但因实现困难放弃
以上方案均未解决问题,恳请协助排查该CORS配置异常。
内容的提问来源于stack exchange,提问作者Moudou Doumou
相关产品推荐
相关产品推荐

