如何修复本地JSON Fetch加载报错?已上传至CodeSandbox示例
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:
Place your JSON file in the right location
In React-based environments like your sandbox, static assets like JSON files need to live in thepublicfolder. Make sure yourdata.jsonis directly insidepublic—not insrcor any subfolder ofsrc.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");Avoid infinite re-renders
Right now, you're callingonMap()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'suseEffecthook to run the fetch only once when the component mounts.Add error handling
Wrap your fetch logic intry/catchblocks and check if the request was successful (using theokproperty 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.jsontells the server to look for the file in thepublicfolder, which is the correct location for static assets in React. useEffectwith 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

