React调用Spring Boot API仅DELETE请求出现CORS问题求助
解决思路
1. 修复前端URL拼接问题
错误提示里的[object%20Object]明确说明,你拼接URL时传入的id是一个对象而非预期的数值类型,导致请求URL格式错误,进而触发CORS预检失败。
修改前端代码,确保id是原始数值类型:
const borrarProducto = async (id) => { try { // 强制转换id为数值,避免对象类型导致URL错误 const productId = Number(id); const res = await axios.delete(`http://localhost:8080/api/borrar-producto/${productId}`); console.log(res); } catch (error) { console.log(error); } };
也可以使用模板字符串直接拼接,同时确保传入的id本身是有效数值:
const borrarProducto = async (id) => { try { const res = await axios.delete(`http://localhost:8080/api/borrar-producto/${id}`); console.log(res); } catch (error) { console.log(error); } };
2. 完善后端CORS配置
CORS预检请求使用OPTIONS方法,虽然你配置了allowedMethods包含DELETE,但需要显式允许OPTIONS请求,避免预检被拦截:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedOrigins("*") .allowedHeaders("*"); } }
3. 显式指定控制器请求方法
原控制器方法未限定请求方式,显式指定DELETE方法可避免请求匹配歧义:
@RestController @RequestMapping("/api") public class ProductoControlador { // 用@DeleteMapping替代@RequestMapping,更清晰 @DeleteMapping("/borrar-producto/{id}") public ResponseEntity<String> eliminarProducto(@PathVariable Long id) { servicio.borrarProducto(id); return new ResponseEntity<>("Se eliminó el producto", HttpStatus.OK); } }
4. 排查Spring Security拦截(若使用)
如果项目集成了Spring Security,它可能拦截OPTIONS预检请求,需在Security配置中放行:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() .authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行所有OPTIONS请求 .anyRequest().authenticated(); // 其他请求按需配置权限 } }
5. 验证后端接口可用性
直接用Postman或浏览器发送DELETE请求:http://localhost:8080/api/borrar-producto/1(替换1为真实存在的id),如果能正常返回响应,说明后端接口本身无问题,问题集中在前端请求的参数处理上。
内容的提问来源于stack exchange,提问作者Agustín Sosa
相关产品推荐
相关产品推荐

