【问题标题】:Fetching JSONP with React Native使用 React Native 获取 JSONP
【发布时间】:2026-01-20 18:35:01
【问题描述】:

我正在尝试将此 API https://www.petfinder.com/developers/api-docs 与 React Native 一起使用。我遇到的问题是它返回 JSONP 而不是 JSON,所以使用 fetch 在 JSON 错误中给了我一个意外的令牌。我尝试使用像 fetch-jsonP 这样的库,但是因为没有文档(与 jquery 相同),所以在 React Native 中不起作用,有什么想法可以使用 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;

【问题讨论】:

  • 你试过this吗?
  • 是的,当我使用 fetch 调用运行该代码时,我得到“无效的 JSONP 响应”,所以我抛出了错误

标签: react-native jsonp fetch


【解决方案1】:

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

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

【讨论】:

  • 是的,这最终成为了解决方案