我正在尝试将此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;
答案 0 :(得分:0)
JSONP仅在浏览器中有效,不适用于移动设备。不要尝试使用fetch-jsonP或任何JSONP库,因为它们依赖document.createElement('script')获得跨域支持。在手机上,跨域毫无意义。
正如我在petfinder.com上看到的那样,仅当您提供回调时才使用JSONP。如果您不这样做,我希望得到一个正常的JSON响应。