Tomcat下部署vue项目[history模式]

2019-07-13  本文已影响0人  漫漫江雪

项目发布后通常有两种访问方式,
第一种: IP+端口直接访问的方式,如 http://192.168.4.160:6090/
第二种:IP+端口+项目名,如 http://192.168.4.160:6090/huangshi/

  1. IP+端口的方式需要修改Tomcat -> conf/server.xml, 增加Context节点, 设置 docBase="/huangshi" 其中的huangshi就是webapps目录下的项目名称(文件夹名)<Context docBase="/huangshi" path="" reloadable="true" />
    如下图

    image.png
  2. IP+端口+项目名 这种方式的部署需要在vue项目源码上作些修改
    首先 路由的配置上,增加 base:'项目名称'

const router = new Router({
  base: 'huangshi',
   mode: 'history',
  linkActiveClass: 'active',
  linkExactActiveClass: 'active',
  routes: routes
})

export default router

其次修改 vue.config.js,增加publicPath配置项,如果没有这个文件,手动增加
比如:

module.exports = {
  devServer: {
    port: 8888,
    proxy: {
      '/api': {
         target: 'http://192.168.4.189:8085/api',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      },
  publicPath:'huangshi'
}

因为是history模式, 要防止在路由下刷新变成404错误,这需要让tomcat都定位到首页,也就是index.html页, 在项目目录下新建WEB-INF文件夹, 接着在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>

大致意思就是 服务端404时就去到index.html页,这样客户端的history模式路由就会生效。

上一篇 下一篇

猜你喜欢

热点阅读