Unexpected token 'o', "ok" is not valid JSON”
🚨 错误信息
Unexpected token 'o', "ok" is not valid JSON”
🤖 AI解决方案
json
{
"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):
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);
});