【问题标题】:how to handle React axios how to handle net::ERR_CONNECTION_REFUSED如何处理 React axios 如何处理 net::ERR_CONNECTION_REFUSED
【发布时间】:2020-02-14 12:27:10
【问题描述】:

之前有人问过,但是如果我仍然在控制台中按照解决方案进行操作,则会出现一个粗俗的错误:-

    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 网络::ERR_CONNECTION_REFUSED

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

【问题讨论】:

  • 你有没有想过这个问题?我有一个非常相似的问题让我发疯

标签: reactjs axios


【解决方案1】:

如果您使用的是节点服务器,请在服务器端安装 cors 包:

npm i cors --save 

在服务器端的 index.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);
    })
}

【讨论】:

  • 没有同样的错误。只改变 app.use(cors());到 App.use(cors());否则没有定义'app'。顺便说一句,我添加了 const cors= require('cors'); App.use(cors());就在 index.js 的所有 imorts 之后
【解决方案2】:

这样试试

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);
    })
}

【讨论】:

  • 它甚至使情况变得更糟。错误:- 未捕获的类型错误:无法读取 App.getExchangeAmount (App.js:36) 处未定义的属性“preventDefault”。顺便说一句,我没有为 getExchangeAmount 传递任何参数
  • 我推送到我的 Github。这是总项目代码。我分享了实际代码的链接:- github.com/madsum/currencyconverter_back_and_front/blob/master/…
  • 在您的 Demo.js 中,您甚至没有发现 axios 调用的任何异常。因此,如果服务器未运行或其他错误,则会显示错误:- 未捕获(承诺)错误:网络错误。这个问题的重点是如何避免或抓住这个?
猜你喜欢
  • 2015-06-07
  • 1970-01-01
  • 2019-10-17
  • 2017-10-02
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
相关资源
最近更新 更多