You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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参数同时存在会导致请求逻辑冲突,返回错误响应。

修正步骤

  1. 将fetch中的单引号替换为反引号,正确解析模板变量:
const response = await fetch(`${API_URL}&s=${title}`);
  1. 修改API_URL为基础请求地址,移除i=tt3896198参数:
const API_URL = "https://www.omdbapi.com/?apikey=ed530378";
  1. (可选)增加响应校验,避免非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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 11:48:20