React应用连接Express REST API时JSON解析错误求助
解决React连接Express API时JSON解析错误的问题
错误本质
你遇到的Unexpected token '<'错误,核心原因是fetch请求返回的不是预期的JSON数据,而是HTML页面。通常由两个问题导致:
- React开发服务器和Express API使用了同一个默认端口(3000),请求被React服务器拦截,返回了React首页的HTML代码
- Express路由未正确配置,或API未在指定端口启动
分步解决方案
1. 完善Express API配置并修改端口
你只提供了路由代码,需要确保Express主文件(如app.js)正确挂载路由、处理跨域并更换端口:
const express = require('express'); const app = express(); const usersRouter = require('./routes/users'); // 假设你的路由文件存放在routes/users.js const cors = require('cors'); // 安装cors处理跨域问题 // 启用跨域支持 app.use(cors()); // 挂载/users路由 app.use('/users', usersRouter); // 设置API端口为3001(避开React默认的3000端口) const PORT = 3001; app.listen(PORT, () => { console.log(`API运行在http://localhost:${PORT}`); });
操作步骤:
- 安装cors依赖:
npm install cors - 启动API服务:
node app.js(用nodemon可自动重启:npx nodemon app.js)
2. 修正React的fetch请求地址
修改App.js中的请求URL,指向Express API的端口,并添加错误处理:
componentDidMount() { fetch("http://localhost:3001/users") .then((response) => { // 先校验请求是否成功 if (!response.ok) { throw new Error(`请求失败:${response.status}`); } return response.json(); }) .then((res) => { if (res && res.data) { console.log(res.data); this.setState({ users: res.data }); // 将数据存入组件state } }) .catch((err) => { console.error('请求出错:', err); // 捕获并打印错误信息 }); }
3. 渲染获取到的数据
修改render方法,把state中的用户数据渲染到页面:
render() { return ( <div className="App"> <h1>user data</h1> <ul> {this.state.users.map(user => ( <li key={user.id}> {user.name} ({user.Abrv}) </li> ))} </ul> </div> ); }
验证流程
- 先启动Express API,确认控制台输出
API运行在http://localhost:3001 - 再启动React应用(
npm start),访问http://localhost:3000 - 打开浏览器控制台,可看到打印的用户数据,页面也会渲染出用户列表
内容的提问来源于stack exchange,提问作者user20077666
相关产品推荐
相关产品推荐

