首页 > 解决方案 > 在 chrome 和 firefox 中获取 api 响应是不同的

问题描述

我调用了一个 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

谢谢

标签: javascriptreactjsfetch-api

解决方案


请尝试以下代码:

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
          }
      );

推荐阅读