1. 程式人生 > >vue生產環境遇到跨域問題

vue生產環境遇到跨域問題

開發環境下我們需要使用nginx做代理,例如介面為http://ip/api,我們則可以將api介面代理出去。

所用技術:docker,nginx。

講一下邏輯:
1.vue專案打包,打包到dist資料夾下。
2.nginx做容器,並且代理/api介面。(其他介面就繼續加location)
3.使用docker來啟動nginx。

下面是nginx的配置:(儲存為 web.conf 檔案)

server {
	listen 80 default_server;
	listen [::]:80 default_server;
	client_max_body_size 10M;

	root /
web; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name _; location / { root /web; index index.html index.htm; } location /api { add_header 'Access-Control-Allow-Origin' '*'; proxy_pass http:
//ip/api; } }

我這裡有一個寫好的docker檔案,可以根據自己所使用進行修改。

version: '2'
services:
    web:
        image: nginx:latest
        volumes:
            - ./web.conf:/etc/nginx/conf.d/mysite.template
            - ./dist:/web
        ports:
            - 80:80
        command: /bin/bash -c "envsubst < /etc/nginx/conf.d/mysite.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"

開啟網站http://localhost/,即可,現在可以測試還存在有跨域請求。