我正在尝试将此 API https://www.petfinder.com/developers/api-docs与 React Native一起使用。我遇到的问题是它返回 JSONP 而不是 JSON,因此使用 fetch 在 JSON 错误中给了我一个意外的令牌。我尝试使用像 fetch-jsonP 这样的库,但是这在 React Native 中不起作用,因为没有文档(与 jquery 相同),任何想法如何使用 React Native 获取 jsonP 数据?
应用程序.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 响应。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句