vue-router路由使用 history 模式时,后端SpringBoot如何配置

当我们使用Vue开发时,一般会用到vue-router来作为前端路由,实现单页应用。vue-router提供了两种模式模拟一个完整的 URL:hash模式和history模式。

hash模式:使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。

//查看id为1的文章
http://localhost:8888/#/view/1
  • 1
  • 2

history模式:URL 就像正常的 url,比较好看。

//查看id为1的文章
http://localhost:8888/view/1
  • 1
  • 2

vue-router默认是使用hash模式的,不需要额外的配置,如果我们想使用history模式该如何配置呢?

1 前端:vue-router的mode: ‘history’

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})
  • 1
  • 2
  • 3
  • 4

2 后端:我是使用SpringBoot,要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。详细看vue-router的官方文档

SpringBoot默认匹配不到URL时,会返回一个默认的页面,所以可以配置一下默认的配置Bean。

@SpringBootApplication
public class BlogApiApplication {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(BlogApiApplication.class);
        app.run(args);
    }


    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {

        return new EmbeddedServletContainerCustomizer() {
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {

                ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");

                container.addErrorPages(error404Page);
            }
        };
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

这样就可以使用history模式了。

猜你喜欢

转载自blog.csdn.net/lyn1772671980/article/details/80816960