Unable to load second level routing page in vuejs after refreshing it

时间:2018-03-08 22:09:12

标签: javascript vue.js vue-component vue-router

I have my VueJS app running. It is working fine but the only issue is that when I try to refresh the second or third level routing pages, it shows me an error message in the console, stating:

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

For eg.,

http://localhost:8080 renders me home page. No issue on refreshing.

http://localhost:8080/details renders details page. No issue on refreshing.

http://localhost:8080/details/users renders users page. On refreshing, it errors out.

I also have similar links defined for http://localhost:8080/details/assets and http://localhost:8080/details/groups which all errors out on page refresh. Here is the code for 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');

and for 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}
];

Any idea on how to fix this issue?

1 个答案:

答案 0 :(得分:2)

正如vue-router

的官方文件所述
  

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

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

但是,当您刷新页面时,请求会直接发送到后端,从而导致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"));
    }
}

希望它适合你!