使用Nginx +Tomcat 前后端分离部署Vue.js +Java Web

项目结构

  1. nginx 部署Vue.js前端
  2. Tomcat 部署Java Web

部署思路

  1.  vue.js 源码rpm build 后放nginx服务所在机器,配置好nginx静态网站路径
  2. Tomcat 部署对应的Java ee web应用后端
  3. nginx进行前端访问后端时的路由转发,替代在vue.js开发时dev模式的nodejs转发作用

需要处理的问题

  1. 登录验证

后端为Java应用,所以后端采用HttpComponents Client模拟登录的方式

在前端发起的登录请求逻辑里进行模拟登录,之后将JSESSIONID cookie设置到前端登录后的响应response中

客户端浏览器拥有这个seesion id,再次访问后端服务的时候就能验证通过了

   final String login = "这里放实际登录请求地址";
        final HttpUriRequest post = RequestBuilder.post(login).addParameter("username", vo.getUserName()).addParameter("password", vo.getPassword()).addParameter("checkCode", "11").build();
        try (final CloseableHttpClient client = HttpClients.custom().build()) {
            CloseableHttpResponse mockResp = client.execute(post);
            Header[] mockRespHeader = mockResp.getAllHeaders();
            for(Header header : mockRespHeader){
                if("Set-Cookie".equals(header.getName())  ){
                    if(header.getValue()!=null && header.getValue().contains("JSESSIONID")){
                        resp.setHeader("Set-Cookie",header.getValue());
                    }else{
                        resp.addHeader(header.getName(),header.getValue());
                    }

                }

            }
        } catch (IOException e) {
           
        }

      2. 请求跨域问题

  •            nginx解决方式

 

add_header 'Access-Control-Allow-Origin' '*';

add_header 'Access-Control-Allow-Credentials' 'true';

add_header 'Access-Control-Allow-Methods' 'GET, PUT, POST, DELETE, OPTIONS';

add_header 'Access-Control-Allow-Headers' 'Content-Type,*';
  •            Java后端加Filter方式
  public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(request, resp);
    }
    

开始操作

  1. 配置Vue.js 项目后端请求ip:port 
  2. 配置Vue.js 项目打包配置
'use strict'

const path = require('path')

module.exports = {
  dev: {

  
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        // 这个地址会在打包的时候起作用,打包时只改这个就行了
        target: 'http://后端服务IP:端口',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },

    host: 'localhost',
    port: 8888, 
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false,


    
    devtool: 'cheap-module-eval-source-map',

    cacheBusting: true,

    cssSourceMap: true
  },
// 这个是打包的配置
  build: {
   
    index: path.resolve(__dirname, '../dist/index.html'),

   
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
// 这个路径只能写成/ ,否则nginx部署的网站会出现css/js 找不到的情况
    assetsPublicPath: '/',

    productionSourceMap: true,
    
    devtool: '#source-map',

  
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    bundleAnalyzerReport: process.env.npm_config_report
  }
}

3.配置Vue.js为History模式

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

4.在Vue.js项目下执行npm bulid 

5.拷贝打包好的dist 目录到nginx 所在服务器上

6.配置nginx


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
	include mime.types;
	default_type application/octet-stream;

	proxy_read_timeout      60m;#解决上传文件过大超时
	
	server {
    listen 999;
    server_name localhost 192.168.20.200;
	client_max_body_size 2G;#解决上传文件过大

    charset utf-8;
    #配上Vue.js 的打包后的资源路径
    root J:/ContainerCloudPlatform/CCP_180517/cloud/cloud-vue/dist; 
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
    location @rewrites {
        rewrite ^(.+)$ /index.html last;
    }
    #上面两个location是配的静态资源
    #下面这个是配的服务转发
	location /api {
        #修正uri
		rewrite ^/api/(.*) /$1 break;
        #后端服务地址
		proxy_pass  http://后端Tomcat IP:端口;
        #Cookie重设,保证登录JSESSIONID不会丢失
		proxy_cookie_path / /api;

	}

	}

}

7.部署Tomcat  及其Java web后端应用

   这个就太简单了,省略

问题:

  1. 后端服务转发问题

         打包之后,前端为js,所以其实访问后端请求是从浏览器发起的,所以需要nginx进行指定的uri转发

         比如,我的就是/api开头的请求需要转发到后台

       2.文件上传问题

         文件上传,主要会产生两个问题

  • 请求超时
    1.设置前端请求超时时间
    2.设置nginx超时时间
      proxy_read_timeout      60m;
    
  • 文件过大
    1.设置nginx上传文件大小限制
    	client_max_body_size 2G;
    2.如果有需要,检测后端服务是否有上传文件大小限制
    

    注意:如果上面都没问题,还是上传出错,我的情况就是服务器是云端,服务器提供者进行了限制,一般为文件大小

猜你喜欢

转载自blog.csdn.net/kaizhao110/article/details/81233772