使用Redux Thunk获取JSON数据时遭遇SyntaxError错误求助
解决Redux Thunk fetch数据时的SyntaxError: Unexpected token '<'错误
这个错误的核心原因是:你请求的../../menu.json路径不正确,服务器返回了HTML页面(大概率是404错误页面),而代码尝试把HTML解析成JSON,因此抛出语法错误。
解决步骤
1. 确认静态文件的正确存放位置
如果是Create React App或类似的前端框架项目:
- 静态资源(如JSON文件)必须放在
public文件夹下,这个目录是项目的静态资源根路径,能直接通过浏览器访问。 - 如果你的
menu.json放在src目录下,无法通过fetch直接访问,需要改用文件导入的方式。
2. 修正fetch路径(针对public文件夹下的JSON)
将Thunk函数中的fetch('../../menu.json')修改为根路径访问:
export const fetchCategoriesAsync = () => async (dispatch) => { dispatch(fetchCategoriesStart()) try { // 根路径指向public文件夹下的menu.json const response = await fetch('/menu.json'); // 新增响应状态检查,提前捕获404等错误 if (!response.ok) { throw new Error(`请求失败: ${response.status}`); } const categoriesArray = await response.json() dispatch(fetchCategoriesSuccess(categoriesArray)); } catch (error){ dispatch(fetchCategoriesFailed(error)); } }
3. 替代方案:直接导入JSON文件(针对src目录下的JSON)
如果menu.json在src目录里,无需使用fetch,直接导入即可:
import menuData from '../../menu.json'; export const fetchCategoriesAsync = () => async (dispatch) => { dispatch(fetchCategoriesStart()) try { dispatch(fetchCategoriesSuccess(menuData)); } catch (error){ dispatch(fetchCategoriesFailed(error)); } }
4. 验证路径正确性
本地开发时,直接在浏览器地址栏访问http://localhost:3000/menu.json:
- 能看到JSON内容 → 路径正确
- 返回404或HTML页面 → 文件位置错误,需调整文件存放路径或请求路径
内容的提问来源于stack exchange,提问作者AlexGherasim
相关产品推荐
相关产品推荐

