nginx处理vue打包文件后的跨域问题

起因

在vue文件打包后,项目脱离了vue配置的反向代理配置,还是会报跨域的错误,或者直接打不开本地文件,
但是此刻我们想打开打包后的文件,测试一下文件有没有错误,因为经常会存在开发阶段没有问题,打包后项目就各种问题,此时我们可以利用nginx处理跨域,其实vue配置也是利用的这个

nginx处理vue打包文件后的跨域问题

安装

先在官网下载nginx 注意版本 运行的环境 我这里用的是windows 然后解压下来就好了

vue修改配置

在vue项目文件中也是利用反向代理处理的

proxyTable: {
      '/preExam': {     
        target: 'http://10.0.0.71', //服务器地址
        changeOrigin: true,
        pathRewrite: {
          '^/preExam': '/preExam'
          //这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
        }
      }
    },

在vue请求接口时

this.$axios.post("/preExam/api/user/login/system", {}).then(res => {
      this.system = res.data.data;
      sessionStorage.setItem('system', res.data.data);
    }).catch(function (error) {
      console.log(error);
    });

此时vue在开发阶段运行后就处理了跨域问题,但是打包后的文件还是存在跨域,接下来我们利用nginx处理

nginx修改配置

解压后的文件找到下图

 server {
        listen       8000;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   C:/Users/Sean.S/Desktop/dist;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
        location  /preExam {
			proxy_pass   http://10.0.0.71/preExam; 
		}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

如图修改

第一处修改是你要开启的端口号
第二处修改是你打包后的文件地址
第三处修改是vue代理的接口地址

必须注意的问题
不要在后面加注释 否则可能会启动不了nginx
每一次启动要把前一次的nginx的进程关掉

最后

启动双击exe文件
运行你修改的端口地址

成功运行打包的文件,并且有数据解决了跨域


完美运行 结束

posted @ 2020-11-04 10:26  有风吹过的地方丨  阅读(2609)  评论(0编辑  收藏  举报