解决单页应用 history 模式下部署 tomcat 刷新页面出现 404

朱雀 2021-03-24 08:24 1275阅读 0赞

我们以当下最流行的 JS 框架 vue 为例,其路由跳转一般结合 vue-router 进行,而 vue-router 默认用 hash 来模拟整个完整的 URL(如:http://www.dandelioncloud.cn/#/archives/17),页面间跳转不会重新加载。

如果你感觉这种链接比较丑,可以采用 history 模式,这样 URL 看过去就比较正常美观,如:http://www.dandelioncloud.cn/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,内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  5. version="3.1" metadata-complete="true">
  6. <display-name>Router for Tomcat</display-name>
  7. <error-page>
  8. <error-code>404</error-code>
  9. <location>/index.html</location>
  10. </error-page>
  11. </web-app>

或者更暴力一点,直接修改 tomcat 目录下的 conf/web.xml,在 节点中增加如下内容:

  1. <error-page>
  2. <error-code>404</error-code>
  3. <location>/index.html</location>
  4. </error-page>

配置完成后,重启下 tomcat,再刷新页面看看,是不是已大功告成?

该方式同样对 uni-app 等开发的单页应用有效。

发表评论

表情:
评论列表 (有 0 条评论,1275人围观)

还没有评论,来说两句吧...

相关阅读