首页 文章

刷新后无法在vuejs中加载二级路由页面

提问于
浏览
2

我运行了VueJS应用程序 . 它运行正常,但唯一的问题是,当我尝试刷新第二级或第三级路由页时,它会在控制台中显示一条错误消息,说明:

Failed to load resource: the server responded with a status of 404 ()

例如,

http://localhost:8080呈现给我主页 . 刷新没问题 .

http://localhost:8080/details呈现详细信息页面 . 刷新没问题 .

http://localhost:8080/details/users呈现用户页面 . 在刷新时,它会出错 .

我也为http://localhost:8080/details/assetshttp://localhost:8080/details/groups定义了类似的链接,页面刷新时出现所有错误 . 这是 main.js 的代码:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'

import { routes } from './routes';


Vue.use(VueRouter);

//Vue.config.productionTip = false

const router = new VueRouter({
  mode: 'history',
  routes  
});

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
new Vue(Vue.util.extend({ router }, App)).$mount('#app');

并为 routes.js

import Home from './components/summary.vue'
import Details from './components/details/details.vue'
import Users from './components/details/users/users.vue'
import Assets from './components/details/assets/assets.vue'
import Groups from './components/details/groups/groups.vue'

export const routes = [
    { path: '/', component: Home},
    { path: '/details', component: Details},
    {path: '/details/users', component: Users},
    {path: '/details/groups', component: Groups},
    {path: '/details/assets', component: Assets}
];

有关如何解决此问题的任何想法?

1 回答

  • 2

    正如vue-router的官方文件所述

    为了摆脱哈希,我们可以使用路由器的历史模式,它利用history.pushState API实现URL导航而无需重新加载页面

    因此,只在前端导航不会向后端发送请求,这是您的 Spring 季启动应用程序(您可以从网络流量中看到这一点)

    但是,当您刷新页面时,请求会直接发送到后端,从而导致404错误 .

    要解决您的问题,一个选项可能是将默认404页面设置为 index.html ,建议here

    @Component
    public class WebConfiguration implements EmbeddedServletContainerCustomizer {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
            configurableEmbeddedServletContainer.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/index.html"));
        }
    }
    

    希望这对你有用!

相关问题