Get json from jsonp fetch promise

倖福魔咒の 提交于 2019-12-12 12:06:09

问题


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


来源:https://stackoverflow.com/questions/41146650/get-json-from-jsonp-fetch-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!