Get json from jsonp fetch promise

2019-07-05 01:41发布

问题:

I am just starting with react-native, and I'm doing the classic example in the docs as a base...

fetch('https://facebook.github.io/react-native/movies.json')
  .then((response) => response.json())
  .then((responseJson) => {
    return responseJson.movies;
  })
  .catch((error) => {
    console.error(error);
  });

This all works fine with proper json in that example.

However, in my particular case, the only api response available is JSONP and not JSON. No basic JSON is available. So I receive an error about the "(".

So instead of JSON like

{"id": "1", "movies" : [ { "id" : "123" } ] }

I receive JSONP like

?( {"id": "1", "movies" : [ { "id" : "123" } ] });

However, I'm unsure what I can do to get the JSON out of this via the fetch promises ? How can I manipulate the response with one of my own functions, or is there a more natural way ?

So in the first then() I'm unsure what I can do to get out the json (I've tried operating on the response, but that just seems to look at the promise, so I'm unsure how react-native fetch is operating with this).

回答1:

I would suggest using response.text() instead of response.json(), remove the surrounding noise and then parse the JSON string.

fetch('YOUR URL HERE')
        .then((response) => response.text())
        .then((responseText) => {
            const match = responseText.match(/\?\((.*)\);/);
            if (! match) throw new Error('invalid JSONP response');
            return JSON.parse(match[1]).movies;
        })
        .catch((error) => {
            console.error(error);
        });