前端部署:vue跨域配置、打包、nginx本机&远程访问

vue版本 npm版本 2.6.11 8.1.2

⭐前排感谢大佬!!

0 项目说明

服务器和访问其的电脑同属校园网内网中

1 vue跨域配置

两种跨域方式均可,这里采用跨域2

1.1 vue.config.js

打包不会打进去这个文件,本机运行npm run serve而不是用nginx代理打包文件时,可以配一下介个!

module.exports = {
          
   
    devServer: {
          
   
        port: 8090,			// 前端启动端口
        host: 0.0.0.0,
        // 跨域1
        // proxy: "http://localhost:8080"						// 本机运行的后端url
        // proxy: "http://127.0.0.1:4523/mock/1428114"			// mock用
        // 跨域2
        proxy: {
          
   
            /api: {
          
   
                target: http://localhost:8080/,            		// 本机运行的后端url
                // target: http://127.0.0.1:4523/mock/1428114,    // mock用
                ws: true,
                changeOrigin: true,
                pathRewrite: {
          
   
                    "^/api": ""
                }
            }
        },
    },
    lintOnSave: false,
    publicPath: "./"		// 注意这里的改动,防止打包出错
}

1.2 封装axios的文件:/utils/api.js

打包会打进去这个,前端dist文件运行环境发生变化时,base发的url也会相应变化,所以一定要看环境改!

import axios from "axios";
// let base = http://localhost:8090;   // 跨域1,前端端口号8090,仅本机运行
// let base = http://localhost:8090/api;  // 跨域2,前端端口号8090,仅本机运行
// 推荐使用下面这个,这样服务器和非服务器都可使用服务器的ip访问
// let base = http://服务器ip地址:8090;   // 跨域1,前端端口号8090,本机为服务器&远程运行
let base = http://服务器ip地址:8090/api;  // 跨域2,前端端口号8090,本机为服务器&远程运行

export const postRequestJSON = (url, data, params) => {
          
   
  return axios({
          
   
    method: post,
    url: `${
            
     base}${
            
     url}`,
    data: data,
    params: params,
    transformRequest: [function (data) {
          
   
      data = JSON.stringify(data);
      return data
    }],
    headers: {
          
   
      Content-Type: application/json
    }
  });
}

1.3 路由配置文件:/router/index.js

const router = new VueRouter({
          
   
    mode: hash,	// 采用hash模式
    routes
})

2 前端打包

npm run serve	// 保险起见,改完了先serve一下(瞎说)
npm run build

3 服务器的nginx运行配置

修改conf ginx.conf文件:在http块中新建一个server块,具体内容如下,改完后记得重启nginx。

server {
	listen 8090;							# 前端运行的端口号
    server_name 0.0.0.0;					# 全域广播
    autoindex on;							# 开启跨域
    index index.html index.htm index.php;
    root D:WebstormProject打包dist;  # 前端打包文件存储的位置

    location ^~/api/ {		# 这里是把url中的api进行替换
    	proxy_pass http://localhost:8080/;	# 后端url
    }

	client_max_body_size 50m;				# 上传文件大小限制
}

4 访问前端页面

4.1 服务器本机访问

运行nginx,在浏览器地址栏中输入localhost:8090(前端端口号)即可

4.2 非服务器&服务器远程访问

运行nginx,在浏览器地址栏中输入服务器ip地址:8090即可

5 总结

总结一下就是,代码中axios的url才是发送的真实目的地:

经验分享 程序员 微信小程序 职场和发展