React中调用自定义JSON Server时Fetch请求出现SyntaxError报错问题
Hey there, let's break down why you're seeing that frustrating syntax error when making fetch requests to your JSON Server—even though the server seems to be running fine. That error is a dead giveaway that your request is getting back HTML content instead of the JSON you expected, so let's walk through the most common fixes:
1. Double-Check Your Request URL
JSON Server creates API routes directly from the keys in your JSON data file. For example, if your db.json looks like this:
{ "products": [], "orders": [] }
You need to fetch from http://localhost:3000/products or http://localhost:3000/orders—not just the root URL (http://localhost:3000), which returns JSON Server's default welcome page (HTML). If you request a non-existent endpoint (like /product instead of /products), you'll get a 404 HTML page instead of JSON.
Quick fix: Verify your fetch URL matches the exact route names from your JSON file.
2. Inspect the Actual Response Content
Grab your browser's DevTools (hit F12, go to the Network tab), then re-run your fetch request. Click on the request in the list and check the Response tab. You'll probably see something like a 404 page or the JSON Server welcome HTML here.
This will tell you exactly what's going wrong:
- If it's a 404: Your URL is incorrect (refer back to point 1).
- If it's the welcome page: You're hitting the root URL instead of an API route.
3. Validate Your JSON Server Startup Command
Make sure you started the server with the correct JSON file. For example, if your data file is named database.json instead of db.json, you need to specify it explicitly:
json-server --watch database.json
If you added extra flags (like --static to serve static files), ensure you're not accidentally requesting a static HTML file instead of an API endpoint.
4. Add Error Handling to Your Fetch Call
To debug more easily, modify your fetch code to check the response status before trying to parse JSON. This will let you see the raw HTML content causing the error:
fetch('http://localhost:3000/your-route') .then(response => { if (!response.ok) { console.log(`Response status: ${response.status}`); return response.text(); // Get raw HTML instead of forcing JSON parsing } return response.json(); }) .then(content => console.log('Returned content:', content)) .catch(err => console.error('Error:', err));
Running this will show you exactly what HTML is being sent back, making it way easier to fix the root issue.
内容的提问来源于stack exchange,提问作者Christos Segkani

