如何根据响应代码重定向到错误页面



我有一个用来检查天气的api,但它可能会根据情况返回不同的代码。在catch块中的axios.get中,我想根据服务器返回的代码将用户重定向到错误页面。如何做到这一点?我尝试了下面的代码,但它工作错误。出现错误时,首先会出现"cityDoesntExist"页面,然后几乎立即出现"serverDoesntWork"页面

methods: {
async getWeather() {
const cityName = this.$route.params.cityName;
await axios.get(`/api/weather`, {params: { cityName: cityName }})
.then(response => response.data)
.then(data => this.weather = data)
.catch(function (error) {
if(error.response.status === 404) {
router.push({name: 'cityDoesntExist'});
}
if(error.response.status === 500) {
router.push({name: 'serverDoesntWork'});
}
});
},
},

错误也可能是由其他问题引起的,这就是为什么我建议您首先确认收到了响应,然后您可以检查响应的状态,然后使用return关键字,如:

.catch(function (error) {
if (error.response) {
// Request made and server responded
if(error.response.status === 404) {
router.push({name: 'cityDoesntExist'});
return;
}
if(error.response.status === 500) {
router.push({name: 'serverDoesntWork'});
return;
}
} else if (error.request) {
// The request was made but no response was received
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}

参考代码:Axios处理错误

4个小时后,我终于找到了解决方案,而且比我想象的要容易。感谢所有试图帮助我的人!这是我的解决方案:

async getWeather() {
const cityName = this.$route.params.cityName;
await axios.get('/api/weather', {params: {cityName},})
.then(response => response.data)
.then(data => this.weather = data)
.catch(function (err) {
let errJSON = err.toJSON();
console.log(errJSON);
if (errJSON.status === 404) {
return router.push({name: 'cityDoesntExist'});
} else if (errJSON.status === 500) {
return router.push({name: 'serverDoesntWork'});
}
});
}

最新更新