使用React Native获取JSONP

问题描述 投票:0回答:1

我正在尝试将此API https://www.petfinder.com/developers/api-docs与React Native一起使用。我遇到的问题是它返回JSONP而不是JSON,因此使用fetch会在JSON错误中给出一个意外的令牌。我试过使用像fetch-jsonP这样的库,但是那些在React Native中不起作用,因为没有文件(与jquery相同),任何想法如何用React Native获取jsonP数据?

App.js

class Home extends Component {
  componentDidMount() {
    fetch(
      `http://api.petfinder.com/pet.find?format=json&key=${API_KEY}&animal=dog&location=84070&callback=callback`
    )
      .then(res => res.json())
      .then(responseText => console.log(responseText))
      .catch(err => console.log(err));
  }
  render() {
    const width = Dimensions.get("window").width;
    const height = Dimensions.get("window").height;

    return (
      <View>
        <Header
          backgroundColor={darkBlue}
          leftComponent={{ icon: "menu", color: "#fff" }}
          centerComponent={<HeaderTextComponent />}
          rightComponent={{ icon: "home", color: "#fff" }}
        />
      </View>
    );
  }
}

export default Home;
react-native jsonp fetch
1个回答
1
投票

JSONP仅适用于浏览器,不适用于移动设备。不要尝试使用fetch-jsonP或任何JSONP库,因为它们依赖于document.createElement('script')来获得跨域支持。在手机上,跨域没有意义。

正如我在petfinder.com上看到的那样,JSONP仅在您提供回调时使用。如果您不这样做,我希望获得正常的JSON响应。

© www.soinside.com 2019 - 2024. All rights reserved.