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

使用React.js及Fetch API发送GET请求失败,报SyntaxError错误求助

Fixing 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/categories should be http://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 the categories request 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
    Paste http://localhost:5555/categories directly into your browser's address bar. If it doesn't return clean, valid JSON (and has a Content-Type: application/json header 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:32:26