如何在 Axios 中处理 net::ERR_CONNECTION_REFUSED - Vue.js

How to handle net::ERR_CONNECTION_REFUSED in Axios - Vue.js

下面是我的连接请求代码:

doLogin(this.login).then(response => {
        var token = response.data.token;
        localStorage.setItem('AUTH_TOKEN', JSON.stringify(token));
        this.$router.push({name: 'Devices'});
        });
      }).catch(error => {
        console.log(error.response.data.message);
      });

catch() 部分适用于 http 错误(如 400404403..等)。但是当我的服务器离线时,这个脚本只会抛出 net::ERR_CONNECTION_REFUSED。有什么办法可以处理这个错误,让前端用户知道服务器目前离线了?

这里是 doLogin() 函数以防万一,

function doLogin(data) {
  const url   = 'http://localhost:3000/authenticate';
  return axios.post(url,data);
}

您可以像PanJunjie潘俊杰 suggested, or make use of a library like sindresorhus/is-reachable一样验证自己。后者将是我的首选。

干杯!

你可以在 catch 部分试试这个:

catch(error => {
        if (!error.response) {
            // network error
            this.errorStatus = 'Error: Network Error';
        } else {
            this.errorStatus = error.response.data.message;
        }
      })

您应该执行@chithra 在 .then() 中指出的相同验证,因为我在服务器关闭时测试请求时遇到了一个奇怪的问题,"response" 就好像它是成功了。

此外,在 .then() 上使用 response.status 而不是 response.error

您可以使用 拦截器:

axios.interceptors.response.use(
    response => {
        return response
    },
    error => {
        if (!error.response) {
            console.log("Please check your internet connection.");
        }

        return Promise.reject(error)
    }
)

通过使用 npm; JavaScript 运行时环境 Node.js.

的标准包管理器

使用 npm:

npm i axios

接下来,您应该在 src/App.vue 文件中导入 Axios

import axios from 'axios';

您需要在生命周期挂钩上调用它。这里我们将使用 beforeCreated() 生命周期钩子,这是因为我们将能够检索使用 beforeCreated 钩子激活的敏感数据和事件。

 data() {
return {
  network: false,
}; },
beforeCreate() {
axios
  .get("http://localhost:13172/api/product/getproducts")
  .then((response) => {
    console.log(response);
    this.network = true;
  })
  .catch((error) => {
    console.log(error), (this.network = false);
  }); }