首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >捕捉Vuex中的Axios错误以显示404页

捕捉Vuex中的Axios错误以显示404页
EN

Stack Overflow用户
提问于 2021-03-23 14:35:47
回答 1查看 1.3K关注 0票数 1

我正在构建一个应用程序,使用Django Rest框架作为后端,Vue 3用于前端。在我的项目中使用Vuex和Vue路由器,还可以使用Axios在Vuex操作中使用API。但是,当从后端获取失败时,我想不出如何显示404页。我尝试了几种方法,比如将路由器导入vuex并使用router.push({name: 'notfound'})捕获错误,但没有奏效。你对如何做到这一点有什么想法吗?

router/index.js

代码语言:javascript
运行
复制
...
  {
    path: '/route/:category',
    name: 'filteredterms',
    component: Home
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'notfound',
    component: NotFound
  }

store/index.js

代码语言:javascript
运行
复制
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'})
      }
EN

回答 1

Stack Overflow用户

发布于 2021-03-23 16:19:03

您可以使用axios中的interceptor模式来实现这一全局目标:

代码语言:javascript
运行
复制
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)
    }
  }
)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66765313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档