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

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

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

//查看id为1的文章

http://localhost:8888/#/view/1

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

//查看id为1的文章

http://localhost:8888/view/1

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

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

constrouter =newVueRouter({

mode:'history',

routes: [...]

})

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

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

@SpringBootApplication

publicclass BlogApiApplication {

public static void main(String[] args){

SpringApplication app =newSpringApplication(BlogApiApplication.class);

        app.run(args);

    }

@Bean

public EmbeddedServletContainerCustomizer containerCustomizer(){

returnnewEmbeddedServletContainerCustomizer() {

@Override

public void customize(ConfigurableEmbeddedServletContainer container){

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

                container.addErrorPages(error404Page);

            }

        };

    }

}

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容