Unexpected token '<', "<!DOCTYPE "... is not valid JSON

2026年05月21日 11:22 29.86 秒 success

错误信息

Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

AI 解决方案

🔍 错误分析报告

1. 🌐 错误翻译


原文:SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
译文:语法错误:遇到意外的'<'字符,开头的“<!DOCTYPE ...”不是有效的JSON格式。

2. 🎯 原因分析


  • 根本原因:您的代码(通常使用 fetchaxios 等库)期望接收到 JSON 格式的 API 响应,但实际接收到的是一个 HTML 页面(以 <!DOCTYPE 开头)。

  • 具体位置:错误发生在对 HTTP 响应进行 .json() 解析的代码行。

  • 常见场景

  • 1. 请求的 API 路径错误(例如,/api/users 写成了 /api/user)。
    2. 后端服务器出错,返回了默认的错误页面(通常是 HTML)。
    3. 请求被前端或后端的路由/代理重定向到了登录页面、404页面等 HTML 页面。
    4. 跨域请求(CORS)失败,浏览器收到了一个非 JSON 的错误响应。

    3. 💡 解决方案


    在解析 JSON 前,应先检查 HTTP 响应状态和内容类型。

    使用 fetch API 的修复示例:

    fetch('your-api-endpoint')
      .then(response => {
        // 步骤1: 检查网络请求是否成功
        if (!response.ok) {
          throw new Error(`HTTP 错误! 状态码: ${response.status}`);
        }
        // 步骤2: 检查响应内容是否为 JSON
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
          // 如果不是 JSON,读取文本内容用于调试
          return response.text().then(text => {
            throw new Error(`预期为JSON响应,实际收到HTML或其它内容: ${text.substring(0, 100)}...`);
          });
        }
        // 步骤3: 只有在前两步通过后才尝试解析 JSON
        return response.json();
      })
      .then(data => {
        console.log('成功获取数据:', data);
      })
      .catch(error => {
        console.error('请求失败:', error);
      });
    

    使用 axios 的修复示例:

    axios.get('your-api-endpoint')
      .then(response => {
        // axios 会自动处理 JSON 解析,但有时仍会出错
        // 可以在这里添加类型检查
        if (typeof response.data === 'string') {
          // 如果后端错误地返回了字符串(可能是HTML),则手动尝试解析或处理
          try {
            response.data = JSON.parse(response.data);
          } catch (e) {
            throw new Error('接收到非JSON的字符串响应');
          }
        }
        console.log('成功获取数据:', response.data);
      })
      .catch(error => {
        if (error.response) {
          // 请求已发出,服务器用状态码响应
          console.error('服务器返回错误状态码:', error.response.status);
          console.error('响应内容:', error.response.data);
        } else {
          // 请求设置出错或没有收到响应
          console.error('请求设置错误:', error.message);
        }
      });
    

    4. 🛡️ 预防措施


  • 使用开发者工具:在浏览器中打开“开发者工具” (F12),切换到 Network 面板,找到失败的请求,直接查看其返回的 Response 内容和 Status Code,这是最直接的调试方法。

  • 建立健壮的 API 错误处理:在封装的请求工具函数中,统一添加对响应状态码和 Content-Type 头的检查逻辑,避免将非 JSON 内容传递给后续处理代码。

  • 验证 API 端点:在开发时,使用 Postman 或 cURL 等工具单独测试您的 API 接口,确保其端点正确且能按预期返回 JSON。