react native fetch returns Blob instead of JSON after upgrading to 0.24.1
Asked Answered
C

7

11

Hi so I’ve recently upgraded to 0.24.1 and I’m having problems with fetch. I’m getting similar issues as this https://github.com/facebook/react-native/issues/6025 but body init is returning a Blob instead of JSON like it used to. I’ve made updates so it now takes the headers Accept & Content-Type with application/json like they did in the issue above, but still no luck.

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

When I console.log the response I get:

{
  _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""
}
Crannog answered 24/4, 2016 at 7:23 Comment(7)
How do you know Blob is incorrect? Also, what do you get when you log out _bodyBlob and _bodyInit?Burgee
Hi @ChrisGeirman, I reverted back to 0.21.0 to get stuff done. I'll upgrade again tonight & edit my question with the output of _bodyBlob & _bodyInit.Crannog
same here, did you solve it?Sixtasixteen
@ChrisGeirman updated my question to include logging of _bodyBlob & _bodyInit.Crannog
@Greag.Deay unfortunately not yet. If you manage to fix it please provide an answer.Crannog
@Greag.Deay actually I've managed to figure out the problem. I'll provide an answer below...Crannog
I found the answer in another thread #38226050Arteriole
C
17

I probably should have read over https://github.com/github/fetch before posting this question...

Need to use .json() on the response.

return fetch(`${auth0_api}/userinfo`, {
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${access_token}`
  }
})
.then((response) => {
  return response.json();
});
Crannog answered 26/4, 2016 at 15:48 Comment(3)
yep, but .json() didn't help me, I'm using .text() as a temporary hack (i hope lol)Sixtasixteen
This worked for me. I replaced all my return JSON.parse(response._bodyText) with return response.json() and it now works in RN & when debugging in chrome.Collbaith
for me it is not giving in proper format too. i tried .json and .textKarren
N
2

Fetch library has been updated, now is:

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)
})
Nub answered 23/7, 2019 at 15:44 Comment(0)
J
1

.json returns a promise so you may need to let that resolve before logging:

fetch(`${auth0_api}/userinfo`, {
      method: 'GET'})
  .then((response) => response.json())
  .then(responseJSON => console.log('here you go:', responseJSON));
}
Jasonjasper answered 30/4, 2020 at 11:52 Comment(0)
A
0

In my case, I was using cross-fetch and it caused the issue with json():

import fetch from "cross-fetch";

Remove it helped me with transforming to json after.

Argolis answered 17/1, 2019 at 16:14 Comment(0)
G
0

I have returning with response.send (even i have tried res.json(),res.text(), res.end, res.send(data), res.json(data), return data, return data.json(), res.end(data), res.send(JSON.stringify(data)), every combination...)

Like an example below

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

everytime it comes to front-end like that:

> 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

But after futher investigating i found that is realy interesting with json() it is successfull with this front-end

Client.auth(settings.apiBaseUrl, this.state.email, this.state.password)
            .then(response => response.json()).then((data) => {
                var pureLink = data;
            })
Griego answered 24/2, 2019 at 11:24 Comment(0)
M
0

apart from the other answers which are for json() and then it return promise, what I was doing is not giving the header to the fetch. Try that to, my problem solve after giving header to the fetch.

Montgolfier answered 24/2, 2021 at 14:33 Comment(0)
F
-2

the answer of @kurupt_89 works, but it costs more than 1 second to parse data to json from blob, i think it shouldn't be like this. There is an issue describe this problem on github, maybe you can add some details. https://github.com/facebook/react-native/issues/8941


ok, i have changed line 419 of fetch.js(path:node_modules/react-native/Libraries/Fetch/fetch.js), from

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

to

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

and then the response can be easily parse into Json

Fillin answered 22/7, 2016 at 5:53 Comment(1)
Link Only Answer is not advisable. Links may get obsolete . You should add important aspects of code mentioned in the linkCatheycathi

© 2022 - 2024 — McMap. All rights reserved.