Unexpected token 'o', "ok" is not valid JSON”

2025年10月28日 02:20 响应: 3.88秒 状态: success

🚨 错误信息

Unexpected token 'o', "ok" is not valid JSON”

🤖 AI解决方案

{
  "error_message": "Unexpected token 'o', \"ok\" is not valid JSON",
  "translated_message": "意外的标记 'o',\"ok\" 不是有效的 JSON"
}

原因分析

接收到的响应不是有效的 JSON 格式。响应内容是纯文本 "ok",而不是期望的 JSON 对象。

解决方案

在处理 API 响应之前,检查响应体的 Content-Type 是否为 application/json。如果不是,或者解析 JSON 时出错,则应该将其作为普通文本处理。

示例(JavaScript):

fetch('/api/your-endpoint')
  .then(response => {
    if (!response.ok) {
      // 处理 HTTP 错误
      throw new Error('Network response was not ok');
    }
    // 检查 Content-Type
    const contentType = response.headers.get('content-type');
    if (contentType && contentType.indexOf('application/json') !== -1) {
      return response.json(); // 解析为 JSON
    } else {
      return response.text(); // 解析为文本
    }
  })
  .then(data => {
    if (typeof data === 'string') {
      // 处理纯文本响应,例如 "ok"
      console.log('Received text response:', data);
    } else {
      // 处理 JSON 响应
      console.log('Received JSON data:', data);
    }
  })
  .catch(error => {
    console.error('Error:', error);
  });

预防措施

  • 服务端统一响应格式:确保 API 服务端在所有情况下都返回一致的、符合规范的响应格式(JSON 对象或明确的错误响应)。
  • 客户端健壮性:在客户端添加对不同响应格式的处理逻辑,提高代码的容错能力。