我正在构建一个应用程序,使用Django Rest框架作为后端,Vue 3用于前端。在我的项目中使用Vuex和Vue路由器,还可以使用Axios在Vuex操作中使用API。但是,当从后端获取失败时,我想不出如何显示404页。我尝试了几种方法,比如将路由器导入vuex并使用router.push({name: 'notfound'})
捕获错误,但没有奏效。你对如何做到这一点有什么想法吗?
router/index.js
...
{
path: '/route/:category',
name: 'filteredterms',
component: Home
},
{
path: '/:pathMatch(.*)*',
name: 'notfound',
component: NotFound
}
store/index.js
import router from "../router/index.js"
...
async exampleFunc({commit}){
const response = await axios.get(`http://127.0.0.1:8000/api/exampleEndpoint`)
.then(response => {
commit('exampleMutation', response.data)
})
.catch(error => {
if (error.response.status == 404){
router.push({name: 'notfound'})
}
发布于 2021-03-23 08:19:03
您可以使用axios中的interceptor
模式来实现这一全局目标:
import router from 'path/to/your/router'
axios.interceptors.response.use(
//successful callback, we don't need to do anything
(response) => {
return response
},
//check if we received a 404 and redirect
(error) => {
if (error.response.status === 404) {
router.push({name: 'notfound' })
} else {
return Promise.reject(error)
}
}
)
https://stackoverflow.com/questions/66765313
复制相似问题