以下是我的连接请求代码:
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);
}
你可以在 catch 部分尝试这个:
catch(error => {
if (!error.response) {
// network error
this.errorStatus = 'Error: Network Error';
} else {
this.errorStatus = error.response.data.message;
}
})
您可以使用拦截器:
axios.interceptors.response.use(
response => {
return response
},
error => {
if (!error.response) {
console.log("Please check your internet connection.");
}
return Promise.reject(error)
}
)
您应该执行@chithra在
.then()
中指出的相同验证,因为我在服务器关闭的情况下测试请求时遇到了一个奇怪的问题,“响应”就好像它是成功的一样。
另外,在
.then()
上用 response.status
而不是 response.error
进行操作
您可以使用拦截器
yourAxiosInstance.interceptors.response.use(
response => response,
error => {
if (error.code === 'ERR_NETWORK') {
alert("No 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);
}); }