javascript 如何在 Axios 中处理 net::ERR_CONNECTION_REFUSED - Vue.js
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47067929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle net::ERR_CONNECTION_REFUSED in Axios - Vue.js
提问by Jithesh Kt
Below is my connection request code :
以下是我的连接请求代码:
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);
});
the catch()part works fine for http errors (like 400, 404, 403..etc). But when my server is offline this script just throws net::ERR_CONNECTION_REFUSED. Is there any way to handle this error and let the front-end user know that the server is currently offline.?
该catch()部分适用于 http 错误(如400、404、403.. 等)。但是当我的服务器离线时,这个脚本只会抛出net::ERR_CONNECTION_REFUSED. 有什么办法可以处理这个错误,让前端用户知道服务器当前处于离线状态。?
Here is the doLogin() function just in case,
这是doLogin() 函数以防万一,
function doLogin(data) {
const url = 'http://localhost:3000/authenticate';
return axios.post(url,data);
}
回答by chithra
You can try this in the catch part:
你可以在 catch 部分试试这个:
catch(error => {
if (!error.response) {
// network error
this.errorStatus = 'Error: Network Error';
} else {
this.errorStatus = error.response.data.message;
}
})
回答by Sinan Eldem
You may use interceptors:
您可以使用拦截器:
axios.interceptors.response.use(
response => {
return response
},
error => {
if (!error.response) {
console.log("Please check your internet connection.");
}
return Promise.reject(error)
}
)
回答by chrisg86
You could verify yourself like PanJunjie潘俊杰suggested, or make use of a library like sindresorhus/is-reachable. The latter would be my preferred option.
你可以像潘俊杰潘俊杰建议的那样验证自己,或者使用像sindresorhus/is-reachable这样的库。后者将是我的首选。
Cheers!
干杯!
回答by Leo
You should do the same validation that @chithra pointed out in the .then()because i'm having a weird issue when testing requests with my servers down, the "response" comes as if it was a success.
您应该执行@chithra 在 中指出的相同验证,.then()因为在我的服务器关闭时测试请求时我遇到了一个奇怪的问题,“响应”就好像它是成功的一样。
Also, on the .then()do it with response.statusinstead of response.error
另外,在.then()用response.status而不是response.error

