API 获取响应 React Native 应用程序中的 Blob 结构



我正在使用我的 React Native Android 项目中的 Web api。将我的反应本机版本更新到 0.60.3 后,我的响应数据没有返回 JSON,它返回 Blob 数据结构。

这就是我从那时得到的(res=>{...})

请看图片

屏幕截图-2019-07-18-at-17-25-10.png

_bodyInit对象返回 JSON。但是现在它返回了我无法从 Js 代码访问的Blob

我尝试使用函数res.json(),res.text()他们工作了!但这一次我只是在_bodyInit里得到了数据。我无法访问其他参数,例如确定标题等。

这就是我尝试过的。就像我说的,它有效。但它只返回我的数据的响应,而不是其他参数,如ok标头等。

.then((res) => res.json())
.then((res) => {
if (res.ok) {
// No 'ok' element anymore after .json()
}
});

在"开发工具"中,如果我单击"_bodyInit"对象。模拟器在下面给出错误。

屏幕截图-2019-07-18-at-17-32-49.png

您有什么想法可以解决此问题吗? 提前感谢!

ok属性在调用方法之前带有响应json。如果响应包含 json,请调用 json 将正文序列化为 json,如果响应包含 blob,请调用 .blob 将正文序列化为 blob。在此处查看更多响应的内容。

.then((res) => {
console.log("response.ok", res.ok)
// print headers,
console.log("headers", res.headers.forEach(item=>console.log(item)))
// if response if json, call res.json
return res.json()
})
.then((res) => {
// here you will only get json data, not other properties.
console.log("json data is ", res)
});

已解决我找到了两种解决此问题的方法。

  1. 使用.json()后使用.then()
.then((res) => {
if (res.ok) {
res.json().then(res=>{
console.log(res)
})
} else console.log("not ok")
});
  1. 使用asyncawait
.then(async res => {
if(res.ok) {
const response = await res.json()
console.log(response)
} else console.log("not ok")
})

很高兴看到您的其他解决方案。谢谢。

最新更新