Spring Boot+Angular7跨域问题:POST请求被CORS拦截
解决Spring Boot + Angular跨域预检请求错误
首先,你的问题核心是跨域预检(OPTIONS)请求没有得到正确的200 OK响应。浏览器在发送POST这类非简单请求前,会先发送OPTIONS预检请求确认服务器允许跨域,而你的后端没有正确处理这个OPTIONS请求,导致返回非200状态码,触发了CORS报错。
方法一:修复自定义CORS过滤器
你的现有过滤器没有处理OPTIONS请求,需要在doFilter方法中添加逻辑,直接对OPTIONS请求返回200状态,无需继续走过滤器链:
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; HttpServletRequest httpRequest = (HttpServletRequest) request; // 设置CORS响应头 httpResponse.setHeader("Access-Control-Allow-Origin", "*"); httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"); httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-Csrf-Token, Authorization"); httpResponse.setHeader("Access-Control-Allow-Credentials", "false"); httpResponse.setHeader("Access-Control-Max-Age", "3600"); // 处理OPTIONS预检请求,直接返回200 OK if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) { httpResponse.setStatus(HttpServletResponse.SC_OK); return; } System.out.println("********** CORS Configuration Completed **********"); chain.doFilter(request, response); }
另外注意你之前重复设置了Access-Control-Allow-Headers,后面的配置会覆盖前面的,上面的代码已经合并成正确的单条配置。
方法二:使用Spring Boot自带的全局CORS配置(推荐)
自定义过滤器容易遗漏细节,Spring Boot提供了更简洁可靠的全局CORS配置方式,无需编写Filter:
创建一个配置类:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class GlobalCorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 对所有API路径生效 .allowedOrigins("*") // 生产环境建议替换为你的Angular域名,比如http://localhost:4200 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(false) .maxAge(3600); // 预检请求缓存时间,减少重复请求 } }
使用这个配置后,你可以删除之前自定义的CORSFilter和FilterRegistrationBean,Spring会自动处理OPTIONS预检请求,避免出错。
额外检查点
- 确保你的
fpy实体类有正确的getter和setter方法,否则Spring无法将Angular发送的JSON数据映射到实体对象中(虽然这不是当前CORS报错的原因,但会导致后续添加数据失败)。 - 生产环境中,不要使用
allowedOrigins("*"),应该指定具体的前端域名(比如http://your-frontend-domain.com),提升安全性。
内容的提问来源于stack exchange,提问作者user7201941
相关产品推荐
相关产品推荐

