ReactJS发出http请求并在页面上显示结果

时间:2019-05-06 16:18:29

标签: javascript reactjs request axios fetch

我有一个带按钮的搜索栏。单击该按钮时,search_on_click函数将运行。该功能应该检索URL的html并将其显示在页面上。

class App extends Component{
    constructor(props){
        super(props)
        this.state = {
            html: []
        }
        this.search = this.search.bind(this)
    }
    search(){
        const URL = 'https://www.zerochan.net/Re%3AZero+Kara+Hajimeru+Isekai+Seikatsu?s=fav'


        axios.get(URL)
            .then(data =>{
             console.log(data)
                this.setState({
                    query: data
                })
            })
            .catch(function(error){
               console.log(error);
            })

}
    render(){

        return(
         <div>
        <button onClick={() => this.search()}>search</button>
        <div>{this.state.query}</div>
        </div>

这是我到目前为止的代码。问题/问题是:

  1. axios不会console.log html甚至无法运行

  2. 我尝试了提取/请求,但问题或多或少都相同

  3. 有更好的方法吗?
  4. 我不认为这是CORS问题,因为我使用了允许铬扩展的CORS。
    1. .catch()也不记录任何内容来控制台

谢谢您的时间。

1 个答案:

答案 0 :(得分:0)

您尝试获取的URL不是有效的资源。您应该点击一个返回一些数据的URL,在您的情况下,它是一个没有用于传输数据的API的HTML或使您可以访问它的CORS。因此,您将无法获得预期的结果,而axios将无法交付您的请求。

有效API请求https://codesandbox.io/s/jv73ynwz05

的示例
  

componentDidMount()在组件被调用后立即被调用   安装(插入树中)。需要DOM的初始化   节点应该去这里。 如果您需要从远程端点加载数据,   这是实例化网络请求的好地方。

  componentDidMount() {
    // Note the api in the URL path, which means it is a valid endpoint
    axios.get('https://randomuser.me/api/?results=50')
      .then(response => {
        const data = response.data.results;
        this.setState({ data })
      })
      .catch(error => {
        console.log(error);
      })
  }

在此处看到类似的问题:Enable CORS in fetch api

相关问题