仅使用 fetch json.gz 来获取 gzipped json

问题描述 投票:0回答:1
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.

数据.json:

{
  "data":1
}

并且它是用

gzip data.json

压缩的

根据这里的回答这应该有效吗? 如何在没有第三方库的现代浏览器中获取 json.gz?

这可能吗 - 我的标题不够吗?

javascript fetch
1个回答
0
投票

您显示的代码是客户端发出的请求。

在创建对请求(由客户端发出)的响应

时,(由服务器)使用标头 
Content-Type
Content-Encoding

客户端应使用的相应标头名为

Accept
Accept-Encoding

并且 - 正如您问题的 comment 中所指出的 - 标头属于

headers
 对象的 
RequestInit
属性,这是全局
fetch
函数使用的第二个参数。

以下是如何重构所展示的示例代码的示例:

async function example() {
  try {
    const requestInit = {
      headers: {
        Accept: "application/json",
        "Accept-Encoding": "gzip",
      },
    };
    const response = await fetch("./data.json.gz", requestInit);
    const data = await response.json();
    console.log(data);
  } catch (cause) {
    console.error(cause);
  }
}

example();

TypeScript Playground 中的代码


现代浏览器会自动解压缩 gzip 压缩的响应主体。请参阅这些问题以获取更多信息:

© www.soinside.com 2019 - 2024. All rights reserved.