使用Fetch获取gzip压缩JSON文件报错,请求排查原因
请求gzip压缩JSON文件报错问题解决
问题描述
我尝试用Fetch请求gzip压缩的JSON文件,代码如下:
fetch('./data.json.gz',{"Content-Encoding": "gzip" , "Content-Type": "application/json"}) .then(response => response.json()) .then(data => console.log(data)) .catch(err => console.log(err));
执行后报错:
SyntaxError: The string did not match the expected pattern.
原始data.json内容:
{ "data":1 }
该文件通过gzip data.json命令压缩。之前看到相关回答说这操作可行,但实际报错。想问这个需求能不能实现?是不是请求头配置有问题?
解决方案
这个需求完全可以实现,你的核心问题是请求头配置搞反了方向:
- 你设置的
Content-Encoding: gzip是告诉服务器「我发送的数据是gzip压缩的」,但你现在是要从服务器获取压缩文件,应该用Accept-Encoding: gzip告诉服务器「我支持gzip压缩,可返回压缩内容」 Content-Type是服务器响应头字段,用来标识返回内容类型,请求方不需要设置这个头
修正后的代码
fetch('./data.json.gz', { headers: { 'Accept-Encoding': 'gzip' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(err => console.log(err));
额外注意事项
- 服务器配置是关键:如果是静态文件服务器(如Nginx、Apache),需要确保它能正确识别
.gz文件,返回Content-Encoding: gzip和Content-Type: application/json响应头。否则浏览器拿到的是二进制压缩数据,直接调用response.json()就会解析失败,也就是你现在遇到的报错。 - 更规范的做法:不要直接请求
.gz文件,而是请求原始data.json,让服务器自动判断你是否支持gzip,自动返回压缩后的内容——这也是大多数网站采用的方式。
内容的提问来源于stack exchange,提问作者Tock
相关产品推荐
相关产品推荐

