美文网首页vue项目实战项目总结
vue实战(12)——vue实战项目(非根目录)history模

vue实战(12)——vue实战项目(非根目录)history模

作者: wayne1125 | 来源:发表于2019-07-23 15:46 被阅读0次

    一、应用场景

    • 使用vue或react单页面框架的同学应该知道,项目路由模式mode一般都分为hash和history两种,vue中默认是hash模式,这种模式上传到服务器后一般不需要额外配置即可访问,唯一不足的就是访问地址都带个#号,如果项目放到服务器根目录下配置还是比较简单的,根目录下配置可参考之前的一篇文章https://www.jianshu.com/p/1bf6c92f96b5
    • 实际项目开发中大部分项目都是放在非根目录下的,这也是本节所讲的实现方式,通过nginx配置文件修改及打包文件配置修改来实现任何目录下history模式路由配置

    二、nginx配置文件修改

    server {
        listen       80;
        server_name  localhost;
        location / { 
        proxy_pass http://localhost:8000;
        }
      location /active {
          try_files $uri $uri/ /active/index.html;
      }
    
      location /active/api {
           proxy_pass   http://localhost:8888/;
      }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }
    }
    
    8000端口下nginx配置
    server {
        listen  8000;
        server_name   localhost;
        location / {
            root   /usr/project/;
            try_files $uri $uri/ /index.html;  #配合vue项目的history模式去除#时用到
            index index.html;
            client_max_body_size    8m;
        }
    }
    

    配置文件说明

    • 使用try_files方式的前提是服务器安装nginx的时候需要安装相应的模块,我是通过yarn源的方式安装的,包含了所有模块,所以可以直接使用
    • 80端口下根目录会指向8000端口(习惯把项目都放在8000端口下指向的project目录下),同时添加/active访问拦截指向active目录下index.html,同时添加/active/api是为了拦截接口访问
    • 8000端口下root指向的是/usr/project/,此目录放置所有前端项目文件夹,一些node服务端项目也可以放进去

    三、vue项目相关配置

    • vue项目目录下config/index.js
    build: {
        assetsPublicPath: '/active/'
    }
    
    • index.html中引用的外部文件“./static/css/xxx.css”
    <link rel="shortcut icon" href="./static/images/favicon.ico">
    <script type="text/javascript" src="./static/js/sha1.js" ></script>
    
    • router下增加mode为history模式
    export default new Router({
      mode: 'history',
      base: 'active',
      routes: [{
            path:'/',
            name:'Navigation',
            component:Navigation
        }]
    })
    
    • 调用后端接口相关配置
    // utils.js配置文件
    global.api = '/active/api'
    // 调用接口页面
    let response = await axios.get(`${global.api}/dtea-service/user/result?examId=${this.questionId}`);
    
    • 为了本地项目和发布至服务器打包文件保持一致,可以把vue本地代理修改下
    proxyTable: {
      '/api': {
        target: 'http://192.136.12.211:8888',
        changeOrigin: true,
        pathRewrite: {
          '^/active/api': ''
        }
      }
    }
    

    参考文章:https://www.cnblogs.com/liugx/p/9336176.html

    以上就是nginx及vue项目的相关配置,去年9月份的时候就探究过实现方式,限于当时对服务器中配置文件操作不太熟练,之后自己买了个服务器,全程配置了一遍,基本熟悉了相应的配置。希望以后加快学习的步伐,掌握更多的知识!

    flag:最近在做一个Ant Design Pro的管理后台项目,抽空研究下react下history的相关配置 💪

    *******************努力到无能为力 > ^ _ ^ < 拼搏到感动自己*******************

    相关文章

      网友评论

        本文标题:vue实战(12)——vue实战项目(非根目录)history模

        本文链接:https://www.haomeiwen.com/subject/cdkigftx.html