【问题标题】:Axios gets undefinedAxios 未定义
【发布时间】: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 吗?

标签: reactjs axios


【解决方案1】:

浏览器中的 JSON 响应是什么样的? axios 在 data 属性下返回响应数据。

例如,如果您的 JSON 响应如下所示:

{ "value": 
    { "joke": "lol"} 
}

然后你会像访问它

axios.get('https://api.icndb.com/jokes/random')
      .then((response) => {       
        console.log(response.data.value.joke);
      })

【讨论】:

    猜你喜欢
    • 2019-12-18
    • 1970-01-01
    • 2021-07-31
    • 2019-03-30
    • 2021-05-26
    • 2019-01-01
    • 2019-08-26
    • 2021-12-29
    • 1970-01-01
    相关资源
    最近更新 更多