代码之家  ›  专栏  ›  技术社区  ›  masiboo

如何处理React axios如何处理网络::错误_连接_拒绝

  •  0
  • masiboo  · 技术社区  · 5 年前

    之前有人问过,但如果我仍然在控制台中遵循解决方案,就会出现一个粗俗的错误:-

        getExchangeAmount(){
      var url = 'http://localhost:8080/excurrency?currency='+this.state.currency+
                '&exCurrency='+this.state.excurrency+'&amount='+this.state.amount 
    
        axios.get(url)
        .then(response => {
            // success
            this.setState({result: response.data})
        })
        .catch((error) => {
            // handle this error
            console.log('error: '+error);
        })
    }
    

    在控制台中:-

    得到 http://localhost:8080/excurrency?currency=EGP&exCurrency=EGP&amount=1 网络::错误连接被拒绝

    上面是红色,这是一个错误。如何避免或抓住这一点?

    1 回复  |  直到 5 年前
        1
  •  2
  •   mohamed ibrahim    5 年前

    如果您使用的是节点服务器,请安装 科尔斯 服务器端的包:

    npm i cors --save 
    

    在索引中。服务器端的js:

    const cors= require('cors');
    app.use(cors());
    

    那你的代码就行了。。

    如果不使用节点服务器,请尝试以下操作:

        getExchangeAmount(){
      var url = '/excurrency?currency='+this.state.currency+
                '&exCurrency='+this.state.excurrency+'&amount='+this.state.amount 
    
        axios.get(url)
        .then(response => {
            // success
            this.setState({result: response.data})
        })
        .catch((error) => {
            // handle this error
            console.log('error: '+error);
        })
    }
    
        2
  •  -1
  •   Funny Side    5 年前

    试试这个

    getExchangeAmount(e){
    e.preventDefault();
      var url = `/excurrency?currency${this.state.currency}&exCurrency=${this.state.excurrency}&amount=${this.state.amount}`
    
        axios.get(url)
        .then(response => {
            // success
            this.setState({result: response.data})
        })
        .catch((error) => {
            // handle this error
            console.log('error: '+error);
        })
    }