【问题标题】:react native fetch returns Blob instead of JSON after upgrading to 0.24.1升级到 0.24.1 后,react native fetch 返回 Blob 而不是 JSON
【发布时间】:2016-08-17 15:39:57
【问题描述】:

您好,我最近升级到 0.24.1,但在获取时遇到了问题。我遇到了与 https://github.com/facebook/react-native/issues/6025 类似的问题,但 body init 返回的是 Blob 而不是像以前那样的 JSON。我已经进行了更新,所以现在它使用标题 Accept & Content-Typeapplication/json 就像他们在上面的问题中所做的那样,但仍然没有运气。

return fetch(`${auth0_api}/userinfo`, {
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${access_token}`
  }

当我console.log 得到回复时:

{
  _bodyBlob: Blob
    size: 1144
    type: "application/json; charset=utf-8"
  _bodyInit:Blob
    size: 1144
    type: "application/json; charset=utf-8"
  headers: Headers
  ok: true
  status: 200
  statusText: undefined
  type: "default"
  url: ""https://lite.au.auth0.com/userinfo""
}

【问题讨论】:

  • 你怎么知道 Blob 不正确?另外,当您注销 _bodyBlob 和 _bodyInit 时,您会得到什么?
  • 嗨@ChrisGeirman,我恢复到 0.21.0 来完成工作。今晚我将再次升级并使用 _bodyBlob 和 _bodyInit 的输出编辑我的问题。
  • 这里也一样,你解决了吗?
  • @ChrisGeirman 更新了我的问题,包括记录 _bodyBlob 和 _bodyInit。
  • @Greag.Deay 不幸的是还没有。如果您设法修复它,请提供答案。

标签: json react-native blob fetch


【解决方案1】:

在发布这个问题之前,我可能应该阅读https://github.com/github/fetch...

需要在响应中使用.json()

return fetch(`${auth0_api}/userinfo`, {
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${access_token}`
  }
})
.then((response) => {
  return response.json();
});

【讨论】:

  • 是的,但是 .json() 对我没有帮助,我使用 .text() 作为临时黑客(我希望大声笑)
  • 这对我有用。我用return response.json() 替换了我所有的return JSON.parse(response._bodyText),现在它可以在RN 和在chrome 中调试时工作。
  • 对我来说,它也没有以正确的格式给出。我试过 .json 和 .text
【解决方案2】:

Fetch 库已经更新,现在是:

fetch('/users')
.then(function(res){
    res.json().then(function(data) {
       console.log('request succeeded with JSON response', data)
    }).catch(function(error) {
       console.log('Data failed', error)
    });
}).catch(function(error){
     console.log('request failed', error)
})

【讨论】:

    【解决方案3】:

    .json 返回一个承诺,因此您可能需要在记录之前让它解决:

    fetch(`${auth0_api}/userinfo`, {
          method: 'GET'})
      .then((response) => response.json())
      .then(responseJSON => console.log('here you go:', responseJSON));
    }
    

    【讨论】:

      【解决方案4】:

      就我而言,我使用的是 cross-fetch,它导致了 json() 的问题:

      import fetch from "cross-fetch";
      

      删除它帮助我在转换为 json 之后。

      【讨论】:

        【解决方案5】:

        我已经返回 response.send(即使我尝试过 res.json(),res.text(), res.end, res.send(data), res.json(data )、返回数据、返回data.json()、res.end(data)、res.send(JSON.stringify(data))、每一种组合...)

        像下面的例子

            sendDashboardSigninUrl(req, res, next) {
                SecurityTokensService.sendDashboardSigninUrl(req)
                    .then(data => {
                        if(req.body.password == myPwd){
                            console.log("data:"+ JSON.stringify(data));
                            res.send(data); //code return from here with 200 ok
                        }
                        else
                        {
                            console.log("error:");
                            throw new Exception("data Error");
                        }               
                    })
                    .catch(next);
            }
        }
        

        每次遇到这样的前端:

        > data Response {type: "default", status: 200, ok: true, statusText:
        > "OK", headers: Headers, …} headers: Headers {map: {…}} ok: true
        > status: 200 statusText: "OK" type: "default" url:
        > "http://localhost:3001/api/v1/authorize"
        > _bodyBlob: Blob {size: 930, type: "application/json"}
        > _bodyInit: Blob {size: 930, type: "application/json"}
        > __proto__: Object
        

        但经过进一步调查后,我发现 json() 真的很有趣 这个前端很成功

        Client.auth(settings.apiBaseUrl, this.state.email, this.state.password)
                    .then(response => response.json()).then((data) => {
                        var pureLink = data;
                    })
        

        【讨论】:

          【解决方案6】:

          除了针对 json() 的其他答案,然后它返回承诺, 我正在做的不是将标题提供给获取。试试看,我的问题在将标题提供给 fetch 后解决。

          【讨论】:

            【解决方案7】:

            @kurupt_89 的答案有效,但是将数据从 blob 解析为 json 需要超过 1 秒的时间,我认为不应该是这样的。 github上有一个issue描述了这个问题,也许你可以补充一些细节。 https://github.com/facebook/react-native/issues/8941


            好的,我已经从

            更改了 fetch.js(path:node_modules/react-native/Libraries/Fetch/fetch.js) 的第 419 行

            if ('responseType' in xhr && support.blob)

            if ('responseType' in xhr && xhr.responseType && support.blob)

            然后响应可以很容易地解析成Json

            【讨论】:

            • 不建议仅链接答案。链接可能会过时。您应该添加链接中提到的代码的重要方面
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-03-01
            • 2016-11-22
            • 2021-11-04
            • 1970-01-01
            • 2017-03-28
            • 1970-01-01
            • 2019-11-18
            相关资源
            最近更新 更多