从jsonp fetch promise获取json

Ian*_*Ian 4 javascript json jsonp promise react-native

我刚刚开始使用react-native,我正在以文档为基础做经典示例...

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

在这个例子中,这一切都适用于正确的json.

但是,在我的特定情况下,唯一可用的api响应是JSONP而不是JSON.没有基本的JSON可用.所以我收到关于"("的错误.

所以代替JSON就好了

{"id": "1", "movies" : [ { "id" : "123" } ] }
Run Code Online (Sandbox Code Playgroud)

我收到JSONP之类的

?( {"id": "1", "movies" : [ { "id" : "123" } ] });
Run Code Online (Sandbox Code Playgroud)

但是,我不确定我可以做些什么来通过fetch promises获取JSON?如何使用我自己的函数操作响应,还是有更自然的方式?

所以在第一个然后()我不确定我能做些什么来摆脱json(我已经尝试过对响应进行操作,但这似乎只是看看了这个承诺,所以我不确定反应是如何获取的正在运作这个).

d-v*_*ine 9

我建议使用response.text()而不是response.json(),删除周围的噪音,然后解析JSON字符串.

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);
        });
Run Code Online (Sandbox Code Playgroud)

  • 请记住,当CORS标头不可用时,通常会使用JSONP.在这种情况下,如果没有CORS头,`fetch`将无效. (6认同)