【发布时间】:2017-09-27 19:15:02
【问题描述】:
我有 React 组件 FetchQoute,它应该从提供的 URL 获得响应,但它显示的是 undefined ?
class FetchQuote extends Component {
constructor(props) {
super(props);
this.state = {
jokes: []
};
}
componentDidMount() {
console.log(res.value); //undefined
axios.get('https://api.icndb.com/jokes/random')
.then((res) => {
this.setState({data:res.value.joke});//error TypeError: Cannot read property 'joke' of undefined
})
}
}
可以在浏览器中轻松测试该 URL 以正确返回 JSON 数据,包括 res.value.joke
【问题讨论】:
-
您只能向同一个域或启用 CORS 的其他域发出 Ajax 请求。
https://api.icndb.com/jokes/random是否启用了 CORS? -
我不知道,网址是公开的。 axios 有类似 jsonp 的方法吗?
-
我不知道。但即便如此,服务器也必须支持 JSONP。
https://api.icndb.com/jokes/random支持 JSONP 吗?