【问题标题】:Catch Axios Error within Vuex to Show 404 Page在 Vuex 中捕获 Axios 错误以显示 404 页面
【发布时间】:2021-06-20 05:38:24
【问题描述】:

我正在构建一个应用程序,使用 Django Rest Framework 作为后端,使用 Vue 3 作为前端。在我的项目中使用 Vuex 和 Vue Router,以及 Axios 在 Vuex 操作中使用 API。但是,当从后端获取失败时,我无法弄清楚如何显示 404 页面。我尝试了一些方法,例如将路由器导入 vuex 并使用router.push({name: 'notfound'}) 捕获错误,但没有奏效。您对如何实现这一点有任何想法吗?

路由器/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'})
      }

【问题讨论】:

    标签: javascript vue.js axios vuex vue-router


    【解决方案1】:

    您可以使用 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)
        }
      }
    )
    

    【讨论】:

    • 感谢您的回答,但它没有用...我 console.log 状态并且它正在记录它(404)但 router.push 不起作用。它只是将 URL 更改为根 (localhost:8080/),仅此而已。什么都没有显示并注入页面。
    • 如果它重定向到主页,那么notfound 似乎当时没有在路由器级别注册。
    • 让我澄清一下,当我转到“localhost:8080/somegibberishnotfound”时,它会显示未找到的页面,但是当我尝试转到“localhost:8080/route/somegibberishnotfound”时,会出现这种行为,因为我在路由器文件中注册了“/route/:category”。所以这就造成了问题。
    猜你喜欢
    • 1970-01-01
    • 2012-11-22
    • 2012-07-12
    • 1970-01-01
    • 2013-08-27
    • 2013-08-13
    • 1970-01-01
    • 2011-04-08
    • 2016-06-24
    相关资源
    最近更新 更多