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文件
運行你修改的端口地址

成功運行打包的文件,並且有數據解決了跨域


完美運行 結束


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM