使用React Native获取JSONP



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

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

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

最新更新