使用React.js及Fetch API发送GET请求失败,报SyntaxError错误求助
SyntaxError: Unexpected token < in JSON at position 0 in React + Fetch API Hey there! Let's break down why you're hitting this error and walk through actionable fixes.
First off, that error almost always means your server isn't returning valid JSON — instead, it's sending back HTML (like a 404 error page, server error page, or misconfigured response). Since HTML starts with <, the res.json() method chokes trying to parse it as JSON.
Here's how to troubleshoot and fix this:
Fix your request URL first
Looking at your code, you missed two slashes in the URL:http:localhost:5555/categoriesshould behttp://localhost:5555/categories. That missing//is probably causing the request to fail entirely, leading to an HTML error response.Inspect what the server is actually returning
Open your browser's DevTools (F12), go to the Network tab, then trigger the fetch. Click on thecategoriesrequest and check the Response tab. If you see HTML (like a "Page Not Found" message), that confirms the issue isn't with your React code — it's with the request path or server setup.Validate your backend endpoint
Pastehttp://localhost:5555/categoriesdirectly into your browser's address bar. If it doesn't return clean, valid JSON (and has aContent-Type: application/jsonheader in the response), you'll need to fix your backend first. Make sure the endpoint is correctly configured to return JSON data.Add response status checks to your fetch code
Before trying to parse the response as JSON, check if the request was successful. This helps you catch HTTP errors (like 404 or 500) early, instead of trying to parse error HTML as JSON. Here's your updated code:
componentDidMount() { // fetch all categories from the server fetch('http://localhost:5555/categories') .then(res => { // Check if response is successful if (!res.ok) { throw new Error(`Request failed with status: ${res.status}`); } return res.json(); }) .then(categories => { this.setState({ loading: false }); console.log(categories); this.setState({ categories }); }) .catch(err => { this.setState({ loading: false }); console.error('Error fetching categories:', err); }); }
- Double-check CORS settings (if applicable)
If your React app is running on a different port than your backend, make sure your server has CORS enabled. A missing CORS configuration can sometimes lead to unexpected HTML error responses too.
内容的提问来源于stack exchange,提问作者M.Ziad

