发送POST请求时触发CORS错误,求助解决方案
解决跨域POST请求的CORS错误
问题原因
你的React请求中设置了credentials: "include",这会让浏览器在跨域请求时携带Cookie等凭证,但后端未配置响应对应的Access-Control-Allow-Credentials: true头,导致预检请求失败。Postman不受浏览器CORS策略限制,因此能正常调用接口。
解决方案
只需在后端CORS配置中添加允许凭证的设置,二选一即可,不要同时使用两种方式避免冲突:
方案1:修改Controller的@CrossOrigin注解
在CarController的@CrossOrigin注解中补充allowCredentials参数:
@Slf4j @RestController @RequestMapping("/api/cars") @RequiredArgsConstructor(onConstructor = @__({@Autowired})) @CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true") // 新增allowCredentials配置 public class CarController { private final CarService carService; @RequestMapping(method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE) public ResponseEntity<?> insertCar(@RequestBody @Valid CarDto car) { return carService.addCar(car); } }
方案2:修改全局WebConfig配置
在WebConfig的addCorsMappings方法中添加allowCredentials(true):
@Configuration @EnableCaching @ConfigurationPropertiesScan @RequiredArgsConstructor public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://localhost:3000") .allowedMethods("*") .allowCredentials(true); // 新增允许凭证配置 } }
配置完成后重启后端服务,再发送POST请求即可解决CORS错误。
内容的提问来源于stack exchange,提问作者LDropl
相关产品推荐
相关产品推荐

