我正在尝试使用 angularJS 的 $http 服务读取 data.gz 中存在的 json。但我只得到奇怪的符号和字符作为回应。我目前在 nodeJS 服务器上本地运行该应用程序。我在这里遗漏了什么吗?
$http({
url: 'systemRes.10.gz',
method: 'GET'
})
.then(function successCallback(response) {
console.log(response.data); //shows strange characters
});
Click to view the strange characters.
因为文件位于本地目录中,将 header 设置为以下会导致错误:拒绝设置不安全 header “Accept-Encoding”
headers: { 'Accept-Encoding': 'gzip' }
请您参考如下方法:
尝试访问本地 gz 文件将不会提供浏览器解压缩文件所必需的 Content-Encoding header 。
之前的帖子证实了这一点 -> Angular gunzip json file automatically : Refused to set unsafe header "Accept-Encoding"
如果您需要在生产中使用您的 js 文件,您应该尝试使用适当的文件服务器(如 nginx 或 apache)来提供您的文件。 否则,如果它是一次性脚本,您应该考虑使用 http-server ,它提供了 -g 选项,为文件的 gzip 版本提供服务。例如,如果您的文件是 systemRes.10.json.gz,则在您的文件夹中启动 http-server
$ npm i http-server
$ node_modules/.bin/http-server -g
您可以编写以下 js 脚本(使用 fetch,但 $http 行为应该相同)
fetch('http://localhost:8080/systemRes.10.json')
.then(resp => resp.json())
.then(json => console.log(json))
.catch(e => console.error(e))
我对其进行了测试,它提供了 Content-Encoding header ,因此您应该可以进行测试。


