HTTP GET请求是HTTP协议中最常用的请求方法之一,用于从服务器获取资源。当客户端发送GET请求时,服务器通常会返回响应数据,而JSON是当前最常用的数据交换格式之一。
Content-Type
未正确设置为application/json
fetch('https://example.com/api/data')
.then(response => response.text()) // 先获取原始文本
.then(text => {
console.log('原始响应:', text);
try {
const json = JSON.parse(text);
console.log('解析成功:', json);
} catch (e) {
console.error('JSON解析错误:', e);
}
})
.catch(error => console.error('请求失败:', error));
确保响应包含正确的Content-Type
:
fetch('https://example.com/api/data')
.then(response => {
console.log('Content-Type:', response.headers.get('Content-Type'));
if (!response.headers.get('Content-Type').includes('application/json')) {
throw new Error('响应不是JSON格式');
}
return response.json();
})
// ...其余处理
如果响应是gzip压缩的:
fetch('https://example.com/api/data', {
headers: {
'Accept-Encoding': 'gzip'
}
})
.then(response => {
const contentEncoding = response.headers.get('Content-Encoding');
if (contentEncoding && contentEncoding.includes('gzip')) {
// 需要解压处理
return response.blob().then(blob => {
// 使用解压库处理blob
});
}
return response.json();
})
async function fetchJson(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP错误! 状态码: ${response.status}`);
}
const contentType = response.headers.get('Content-Type');
if (!contentType || !contentType.includes('application/json')) {
const text = await response.text();
throw new Error(`预期JSON但收到: ${contentType}, 内容: ${text.substring(0, 100)}`);
}
return await response.json();
} catch (error) {
console.error('获取JSON失败:', error);
throw error; // 或者返回默认值/错误对象
}
}
Content-Type
响应头通过以上方法和步骤,您应该能够诊断和解决大多数HTTP GET请求中的JSON解析错误问题。
没有搜到相关的文章