【问题标题】:Fetch api response in chrome and firefox is different在 chrome 和 firefox 中获取 api 响应是不同的
【发布时间】:2021-01-07 04:43:04
【问题描述】:

我调用了一个 API,返回应该是一个 JSON 对象。当我在 Google chrome、safari、edge 上运行它时,返回的是一个正确的对象。但是当我在 Mozilla 上尝试时,它会返回一个文本: H4sIAAAAAAAA/4yOwU7rMBBF9+8rnu46RuPEbWMv2fADrNhEY3uMLJo4cp1KVdV/R0Ug2MF25tyjc0UoUeB6og5VTtuxwV2RI5zuEMq88nKZFp4FDo/HTXyu8f9TLduK738sM+cFDv6TeL0DD6HM6JBP01mWWCpc4uNJPi4cWj4LXKubdFhrDjKtUqe3GY46rFzbInW6d2BIfkjGitKajDLGsrK7kZUZyerD4InJ3GOqcJM4cYNDTz0pMkrrZ+pdT263f0GHucSc8i/Ql8hf4BDSyHtrvTrExMp4zWoU0opsSEO00SZKP8V/H91u/94DAAD//2TPZVR+AQAA

如果我运行 response.json(); 会返回错误;

谁有解决办法?

这是我的获取 API 代码

fetch(BASE_URL + urlPath, {
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Authorization: `Bearer ${token}`,
  }
})
  .then((response) => {
    return response.json();
  })

这是来自 mozilla 的标头请求:

Accept
    application/json
Accept-Encoding
    gzip, deflate, br
Accept-Language
    id,en-US;q=0.7,en;q=0.3
Authorization
    Bearer xxx
Cache-Control
    max-age=0
Connection
    keep-alive
Content-Type
    application/x-www-form-urlencoded
Host
    api-test.id
Origin
    http://localhost:3000
Referer
    http://localhost:3000/dashboard
TE
    Trailers
User-Agent
    Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:80.0) Gecko/20100101 Firefox/80.0

这是来自 Chrome:

:authority: api-test.id
:method: GET
:path: /test/path
:scheme: https
accept: application/json
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,fr-FR;q=0.8,fr;q=0.7,id;q=0.6
authorization: Bearer xxx
origin: http://localhost:3000
referer: http://localhost:3000/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36

谢谢

【问题讨论】:

  • 你的代码不会返回任何东西
  • @JaromandaX 它在第二个返回一个文本,然后就像我上面提到的那样
  • 不......它没有 - 没有return response.json() - 那么你在哪里看到这些值?在开发者工具网络检查器中?
  • 你对比过两者的请求头和响应头是否有区别?
  • @JaromandaX 抱歉,我忘记写了。这只是我真实代码的一个例子。问题的关键是,它在 Mozilla firefox 上返回一个不正确的文本,它应该是一个 json 对象。其他浏览器返回一个 json 对象,除了 mozilla

标签: javascript reactjs fetch-api


【解决方案1】:

请试试这个代码:

fetch(BASE_URL + urlPath,{headers: {
            'authorization': `Bearer ${token}`,
            'Content-Type': 'application/x-www-form-urlencoded'
        }})
      .then(response=>response.json())
      .then(data=>{
              console.log(data);
              return data
          }
      );

【讨论】:

  • 在 mozilla 上的响应仍然相同(文本)
  • 你确定像我一样使用'then'作为链函数吗?
猜你喜欢
  • 2019-02-05
  • 2012-11-09
  • 2013-01-05
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 2015-02-27
  • 2017-06-04
  • 1970-01-01
相关资源
最近更新 更多