javascript - 在 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
谢谢
解决方案
请尝试以下代码:
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
}
);
推荐阅读
- python - 使用 NLTK 的对象标准化
- javascript - 如何将包含 Json 数据的变量传递给执行 javascript 关键字
- d3.js - d3js 动画水平图表改进
- c - 它不是随机的,而是生成数字序列
- android - 有没有办法使用自定义 NFC-V 命令?
- wpf - WPF-应用渲染变换后需要更新多边形的点值
- google-sheets - Arrayformula - 将动态生成的范围列表相加
- javascript - 如何以角度显示来自snakbar中对象的数据
- jquery - 我的引导导航栏切换没有切换
- angular - 无法在 docker 容器中运行 Angular 测试用例