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

Jit*_* Kt 11 javascript vue.js axios

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

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);
      });
Run Code Online (Sandbox Code Playgroud)

catch()部分工作正常的HTTP错误(例如400,404,403...等).但是当我的服务器离线时,这个脚本就会抛出net::ERR_CONNECTION_REFUSED.有没有办法处理此错误并让前端用户知道服务器当前处于脱机状态.

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

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

Sin*_*dem 12

您可以使用拦截器

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

        return Promise.reject(error)
    }
)
Run Code Online (Sandbox Code Playgroud)

  • 伟大的。我只是将其放入 NextJS (React) `_app.js` 中的 `useEffect()` 中,并使用 React 的全局上下文从任何地方全局显示来自 Material-UI 的 Snackbar。 (3认同)

chi*_*hra 11

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

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

  • 这不允许区分诸如`net :: ERR_CONNECTION_RESET`和`net :: ERR_CONNECTION_REFUSED`之类的错误,以及可能的其他错误状态. (5认同)