ReactJS 调用 SpringBoot 接口 fetch 请求失败,请求排查帮助
ReactJS + SpringBoot 项目 Fetch 请求失败排查求助
我写了一个简单的 ReactJS + SpringBoot 项目,但里面的 fetch 请求无法正常工作。SpringBoot 控制器运行正常,直接访问8080端口能拿到正确的JSON数据,麻烦帮忙排查原因。
React 组件代码
import React, { useEffect, useState } from 'react'; export default function ReactComponent(){ const[models, setModels] = useState([]); const[modelName, setModelName] = useState(''); const fetchModelData = () => { fetch("http://localhost:8080/parcer/all") .then(response => { return response.json() }) .then(data => { setModels(data) }) } useEffect(() => { fetchModelData() }, []) return( <ul> {models.map(model => ( <li key={model.id}>{model.modelName} | {model.price}</li> ))} </ul> ) }
React 应用报错栈
ERROR Failed to fetch TypeError: Failed to fetch at <anonymous>:78:39 at new Promise (<anonymous>) at fetch (<anonymous>:77:18) at fetchModelData (http://localhost:3000/static/js/bundle.js:153:5) at http://localhost:3000/static/js/bundle.js:160:5 at commitHookEffectListMount (http://localhost:3000/static/js/bundle.js:27190:30) at commitPassiveMountOnFiber (http://localhost:3000/static/js/bundle.js:28683:17) at commitPassiveMountEffects_complete (http://localhost:3000/static/js/bundle.js:28655:13) at commitPassiveMountEffects_begin (http://localhost:3000/static/js/bundle.js:28645:11) at commitPassiveMountEffects (http://localhost:3000/static/js/bundle.js:28635:7)
排查方向及解决方案
跨域资源共享(CORS)问题:这是最常见的原因,React运行在3000端口,SpringBoot在8080端口,属于不同源,浏览器会拦截跨域请求。
- 方案一:在SpringBoot控制器类或方法上添加
@CrossOrigin注解:@RestController @CrossOrigin(origins = "http://localhost:3000") @RequestMapping("/parcer") public class ParcerController { // 你的接口方法 } - 方案二:全局配置CORS,创建配置类:
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*"); } }
- 方案一:在SpringBoot控制器类或方法上添加
请求URL或路径错误:确认fetch里的URL和手动访问的完全一致,检查是否有拼写错误(比如
parcer是否应为parser)、端口是否正确。添加错误捕获逻辑:当前代码未处理请求失败场景,补充后能看到更详细的错误信息:
const fetchModelData = () => { fetch("http://localhost:8080/parcer/all") .then(response => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json() }) .then(data => { setModels(data) }) .catch(error => { console.error("Fetch error:", error); }) }检查SpringBoot服务状态:确认SpringBoot确实在8080端口启动,端口未被其他程序占用,配置文件未修改端口。
浏览器环境影响:清除浏览器缓存,禁用广告拦截、隐私保护类插件,这些可能拦截跨域请求。
内容的提问来源于stack exchange,提问作者Константин Николаевич Бояр II
相关产品推荐
相关产品推荐

