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

如何修复本地JSON Fetch加载报错?已上传至CodeSandbox示例

Fixing "Unexpected token < in JSON at position 0" When Fetching Local JSON in React

Hey there! Let's break down why your fetch call is throwing that frustrating error and how to fix it.

What's Causing the Error?

That "Unexpected token <" message almost always means your fetch request isn't getting back JSON—it's receiving HTML instead. 9 times out of 10, this happens because the path to your data.json is wrong, so the server returns a 404 error page (which starts with <html>) instead of your JSON file.

How to Fix It

Here are the key steps to get your JSON loading correctly:

  1. Place your JSON file in the right location
    In React-based environments like your sandbox, static assets like JSON files need to live in the public folder. Make sure your data.json is directly inside public—not in src or any subfolder of src.

  2. Update your fetch path
    Instead of using a relative path like ./data.json, use an absolute path starting with / to point to the root of your static assets:

    const req = await fetch("/data.json");
    
  3. Avoid infinite re-renders
    Right now, you're calling onMap() directly in your component's return statement. This means every time your component renders, it triggers the fetch again—creating an infinite loop. Use React's useEffect hook to run the fetch only once when the component mounts.

  4. Add error handling
    Wrap your fetch logic in try/catch blocks and check if the request was successful (using the ok property of the response) to catch issues like missing files early.

Corrected Code Example

import React, { useEffect } from "react";
import "./styles.css";

export default function App() {
  const onFetch = async () => {
    try {
      const req = await fetch("/data.json");
      
      // Check if the request succeeded
      if (!req.ok) {
        throw new Error(`Failed to fetch: Status ${req.status}`);
      }
      
      const data = await req.json();
      return data;
    } catch (error) {
      console.error("Error loading JSON:", error);
      throw error;
    }
  };

  const loadAndLogData = async () => {
    try {
      const data = await onFetch();
      console.log("Loaded JSON data:", data);
    } catch (error) {
      // Handle the error as needed (e.g., show a message to the user)
    }
  };

  // Run the fetch only once when the component mounts
  useEffect(() => {
    loadAndLogData();
  }, []);

  return <div className="App">Check your browser's console for the JSON data!</div>;
}

Why This Works

  • The absolute path /data.json tells the server to look for the file in the public folder, which is the correct location for static assets in React.
  • useEffect with an empty dependency array ensures the fetch runs only once, preventing unnecessary requests and infinite loops.
  • Error handling helps you debug if the file is still missing or if there's another issue with the request.

内容的提问来源于stack exchange,提问作者user12919356

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 17:47:33