React新手教程遇错:Uncaught (in promise) SyntaxError解析JSON失败
解决方法:Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
错误原因
- 模板字符串使用错误:你在
fetch中用单引号'包裹URL,而模板字符串需要用反引号`才能解析${}变量,导致请求的URL是无效的字面量${API_URL}& s=${title},服务器返回HTML错误页面(而非JSON),解析时就会遇到<报错。 - API参数冲突:原
API_URL包含i=tt3896198(用于查询单个指定ID的电影),和搜索用的s参数同时存在会导致请求逻辑冲突,返回错误响应。
修正步骤
- 将
fetch中的单引号替换为反引号,正确解析模板变量:
const response = await fetch(`${API_URL}&s=${title}`);
- 修改
API_URL为基础请求地址,移除i=tt3896198参数:
const API_URL = "https://www.omdbapi.com/?apikey=ed530378";
- (可选)增加响应校验,避免非JSON响应导致的报错:
在解析JSON前先检查response.ok,处理请求失败的情况。
修正后的完整代码
import React from 'react'; import { useEffect } from 'react'; const API_URL = "https://www.omdbapi.com/?apikey=ed530378"; const App = () => { const searchMovies = async (title) => { try { const response = await fetch(`${API_URL}&s=${title}`); if (!response.ok) { throw new Error(`请求失败:${response.status}`); } const data = await response.json(); console.log('data', data); } catch (error) { console.error('搜索电影出错:', error); } }; useEffect(() => { searchMovies('superman'); }, []); return ( <h1>App For David</h1> ); } export default App;
内容的提问来源于stack exchange,提问作者Sir David Roth
相关产品推荐
相关产品推荐

