Angular发送POST请求被CORS拦截但GET、DELETE正常如何解决
问题排查与解决步骤
1. 修复前端POST请求的URL格式
当前报错的直接原因是POST请求的URL缺少http://协议前缀,浏览器将localhost:8080识别为相对路径而非跨域HTTP接口,直接触发CORS规则拦截。你当前的GET请求已经正确加了协议前缀所以可以正常访问,POST请求漏写了协议。
原错误代码:
this.http.post("localhost:8080/api/repairs/postRepair",newrepair,{headers})
修改后代码:
this.http.post("http://localhost:8080/api/repairs/postRepair",newrepair,{headers})
2. 调整后端POST接口参数接收规则
你当前接口用@RequestParam接收参数,但是前端发送的是Content-Type: application/json格式的请求体,@RequestParam仅能解析URL查询参数、form表单格式的参数,无法解析JSON请求体,就算CORS问题解决后也会报400参数错误。推荐修改为用@RequestBody接收实体参数:
首先定义和前端字段匹配的Repair实体类:
// 需引入lombok的@Data注解,或者手动写getter/setter @Data public class Repair { private String name; private String date; private String description; private Long idCar; }
修改Controller接口代码:
@RequestMapping(method = RequestMethod.POST, value = "/postRepair") public void postRepair(@RequestBody Repair repair){ LocalDate date1 = LocalDate.parse(repair.getDate()); iRepairService.postRepair(repair.getName(), date1, repair.getDescription(), repair.getIdCar()); }
3. 统一CORS配置避免冲突
你当前同时使用@CrossOrigin注解和Spring Security的.cors()配置,容易出现配置优先级冲突,推荐删除Controller上的@CrossOrigin注解,统一在Spring Security配置类中添加全局CORS规则Bean:
@Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); // 测试环境允许所有来源,生产环境替换为实际前端域名 configuration.addAllowedOriginPattern("*"); configuration.addAllowedMethod("*"); configuration.addAllowedHeader("*"); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; }
该配置全局生效,不会导致原有GET、DELETE请求失效。
内容的提问来源于stack exchange,提问作者user14787328
相关产品推荐
相关产品推荐

