实际项目开发中,页面想去掉首页里#,便使用router history模式,但是打包后出现无法加载router-view,空白,点击任意链接无法找到文件。(后端服务器使用是Tomcat)
解决方式:
1. 修改Tomcat安装目录下的conf/server.xml,增加Context标签, 设置 docBase="/app" ,其中的app就是webapps目录下的项目名称(文件夹名)
<Context docBase="/app" path="" reloadable="true" />
在最后加上这句
注意这里
context指上下文,实际上就是一个web项目
path是虚拟目录,访问的时候用127.0.0.1:8080/aaa/*.jsp访问网页
docBase是网页实际存放位置的根目录,映射为path虚拟目录
reloadable="true"表示你修改了jsp文件后不需要重启就可以实现显示的同步
2. 配置路由router/index.js 里 base 属性
这里的 dist 和上文中的项目名称/文件夹名要保持一致
注意:设置好base之后,路由跳转的时候就会带上/dist前缀,比如path为/user路由,跳转过去就是http://192.168.1.xx:8080/dist/
3. 配置config/index.js
publicPath: './', // cc add
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: './',
// assetsPublicPath: '/', //原来
4. 在Tomcat 项目下新建WEB-INF文件夹, 接着在WEB-INF文件夹下新建 web.xml文件,
因为是history模式,要防止在路由下刷新变成404错误,这需要让tomcat都定位到首页,也就是index.html页。
<?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>
服务端404时就去到index.html页,这样客户端的history模式路由就会生效
最终打包后的静态文件放在Tomcat下的webapps/app文件夹中,如下图
至此,浏览器输入IP+端口+项目名称就可以访问到项目了,亲测OK了!!!
参考:TomCat vue 环境部署 | RuoYi