Use Ngnix to publish and proxy the front end

1. Development stage

When vue uses axios to request, during the development stage, you can implement the proxy by configuring the vue.config.js file to solve cross-domain problems:

// axios设置接口路径,某些时候,需要给接口添加统一标识
let url = process.env.NODE_ENV === 'development' ? 'http://本机ip:9090' : 'http://本机ip:9091' 
url = url + '/myweb' //接口统一添加标识
//vue.config.js	
devServer: {
		overlay: { // 让浏览器 overlay 同时显示警告和错误
			warnings: false,
			errors: false
		},
		host: "0.0.0.0",
		port: 9090, // 端口号
		https: false, // https:{type:Boolean}
		open: false, // 配置自动启动浏览器
		hotOnly: true, // 热更新
		// proxy: 'http://后台ip:8082'   // 配置跨域处理,只有一个代理时
		proxy: { // 配置多个跨域
			"/myweb": {
				target: "http://后台ip:8082",
				changeOrigin: true,
				// ws: true,//websocket支持
				secure: false,
				pathRewrite: { //将/myweb替换为"",因为后台接口中其实并没有这个字符串
					"^/myweb": ""
				}
			},
		}
	},

2. Production stage

 In the production phase, it is easiest and most convenient to use Ngnix to publish and proxy the front end.

I usually deploy test projects on my Windows computer, which is very convenient and fast. It is enough if the LAN is available.

1. Related scripts

1.1 Start Ngnix

Create .bat script file

E:
cd "E:\nginx-1.22.0" 
nginx.exe

1.2 Stop Ngnix

Create .bat script file

E:
cd "E:\nginx-1.22.0" 
nginx.exe -s stop

1.3 Restart Ngnix

Create a .bat script file. Note: Every time you modify the nginx.conf file, you need to restart Ngnix to use it.

E:
cd "E:\nginx-1.22.0" 
nginx.exe -s reload

2. nginx.conf configuration

Open nginx.conf and add your server service in the http object:

  # 你的web端系统
    server {
       # nginx启动监听的端口
        listen       9091;
        # 可以是localhost,可以是本机ip地址,如果要给公司其他同事的电脑访问,需要配置为本机的ip地址
        server_name  192.168.0.123; 

         # 解决Failed to load resource: the server responded with a status of 413 (Request Entity Too Large)
         client_max_body_size 100M;

        location @router {
			# Vue项目路由不是真实存在的,所以需要将请求重写到 index.html 中,然后交给真正的 Vue 路由处理请求资源
			rewrite ^.*$ /index.html permanent; 
		};
	     
        # 配置页面中的请求代理的后台地址
	    location /myweb/ {
	           # 需要代理访问的后端服务器地址
	           proxy_pass http://后台ip:9098;
               # 重写路由地址,将/myweb替换为空,因为后台接口没有,这是我们自定义的标识
               rewrite ^/myweb(.*)$ $1 break; 
	    }

       location / {
          # 程序根目录配置,也就是刚刚打包文件放置的目录,npm run build生成的dist文件地址
          root G:\myTestProject\dist;
          index index.html index.htm;
	      # 配置把所有匹配不到的路径重定向到index.html,vue-router的mode是history模式的情况下需要配置,否则会出现刷新页面404的情况
	      try_files $uri $uri/ /index.html;
       }
       
    }

Guess you like

Origin blog.csdn.net/D_lunar/article/details/131327766