代码之家  ›  专栏  ›  技术社区  ›  Jithesh Kt

如何处理Axios-Vue中拒绝的网络::ERR\u CONNECTION\u。js公司

  •  32
  • Jithesh Kt  · 技术社区  · 9 年前

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

    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错误(如 400 , 404 , 403 ..等等)。但是当我的服务器离线时,这个脚本只会抛出 net::ERR_CONNECTION_REFUSED . 有没有办法处理这个错误并让前端用户知道服务器当前处于脱机状态。?

    这是 doLogin ()以防万一,

    function doLogin(data) {
      const url   = 'http://localhost:3000/authenticate';
      return axios.post(url,data);
    }
    
    5 回复  |  直到 9 年前
        1
  •  44
  •   chithra    8 年前

    您可以在catch部分中尝试以下操作:

    catch(error => {
            if (!error.response) {
                // network error
                this.errorStatus = 'Error: Network Error';
            } else {
                this.errorStatus = error.response.data.message;
            }
          })
    
        2
  •  17
  •   Sinan Eldem    7 年前

    您可以使用 :

    axios.interceptors.response.use(
        response => {
            return response
        },
        error => {
            if (!error.response) {
                console.log("Please check your internet connection.");
            }
    
            return Promise.reject(error)
        }
    )
    
        3
  •  2
  •   chrisg86    9 年前

    你可以像这样验证自己 PanJunjie潘俊杰 建议,或利用图书馆 sindresorhus/is-reachable . 后者将是我的首选。

    干杯

        4
  •  1
  •   Leo    8 年前

    您应该进行与@chithra在 .then() 因为我在服务器关闭的情况下测试请求时遇到了一个奇怪的问题,“响应”看起来就像成功了一样。

    此外,在 .然后() 使用 response.status 而不是 response.error

        5
  •  -4
  •   shahrokh1111g    5 年前

    通过使用npm;JavaScript运行时环境节点的标准包管理器。js。

    使用npm:

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