我们以当下最流行的 JS 框架 vue 为例,其路由跳转一般结合 vue-router 进行,而 vue-router 默认用 hash 来模拟整个完整的 URL(如:http://www.yoursite.com/#/archives/17),页面间跳转不会重新加载。
如果你感觉这种链接比较丑,可以采用 history 模式,这样 URL 看过去就比较正常美观,如:http://www.yoursite.com/archives/17,由于这种模式采用 history.pushState 完成页面间跳转,因此与 hash 模式一样无需重新加载。
但是当你手动刷新页面的时候,会发现页面找不到,返回 404 了,这是由于在服务器端匹配不到任何静态资源,因此返回 404。
不过不用担心,总有解决办法,官网(https://router.vuejs.org/zh/guide/essentials/history-mode.html)上已给出各种服务器的解决方式,唯独没有 tomcat 的,这里就补充说明下服务部署在 tomcat 下面的解决方式。
在 tomcat 的 webapps 目录下进入单应用项目文件夹创建 WEB-INF/web.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" metadata-complete="true">
<display-name>Router for Tomcat</display-name>
<error-page>
<error-code>404</error-code>
<location>/index.html</location>
</error-page>
</web-app>
或者更暴力一点,直接修改 tomcat 目录下的 conf/web.xml,在
<error-page>
<error-code>404</error-code>
<location>/index.html</location>
</error-page>
配置完成后,重启下 tomcat,再刷新页面看看,是不是已大功告成?
该方式同样对 uni-app 等开发的单页应用有效。
版权属于:瞭月
本文链接:https://www.lervor.com/archives/20/
版权声明:本文为瞭月原创文章,转载请附上原文出处链接和本声明。