1. 程式人生 > 實用技巧 >nginx docker 解決前後端跨域問題

nginx docker 解決前後端跨域問題

環境:mac for docker

前端: vue

後端: django

解決什麼問題: 解決前後端跨域問題

1、首先通過docker run 執行臨時nginx容器,將下面需要對映的檔案及目錄,全部通過docker cp 命令複製出來

然後將/opt/nginx/conf.d/default.conf檔案, 檔案內容修改如下:

server {
    listen       80;
    #listen  [::]:80;
    server_name  host.docker.internal, localhost, 127.0.0.1;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    keepalive_timeout   70;
		
    gzip on;
    gzip_min_length 200;
    gzip_buffers 4 16k;
    gzip_comp_level 6;
    gzip_types text/plain application/javascript text/css application/xml text/javascript application/json;
    gzip_vary on;
    gzip_disable "MSIE [1-6]\.";
    gzip_proxied any;
		
    # 配置django ,如果符合 /api/ 開頭的url,就轉發到http://127.0.0.1:8000
    location /api/ {
       proxy_pass http://host.docker.internal:8000;
proxy_pass_request_headers on; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } # 配置vue,預設的所有的請求,都轉發到 http://127.0.0.1:8080; 比上面多了幾個配置,因為要支援websocket location / { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://host.docker.internal:8080
; proxy_pass_request_headers on; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } #location / { # root /usr/share/nginx/html; # 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 /usr/share/nginx/html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # 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; #} }

  

2、啟動docker-nginx, 將容器內80埠對映到宿主機的8001埠(8001未使用狀態):

version: '3'
services:
  nginx:
    container_name: nginx
    image: nginx:latest
    ports:
    - 8001:80
    #network_mode: host
    volumes:
    - /opt/nginx/nginx.conf:/etc/nginx/nginx.conf
    - /opt/nginx/conf.d:/etc/nginx/conf.d
    - /opt/nginx/log:/var/log/nginx
    restart: always

3、本地啟動vue(預設是8080埠)和django(預設是8000埠)

4、此時nginx 開始監聽本地的8000埠和8080埠,所以開啟前後端工程都要用8001了:

http://127.0.0.1:8001/

前端工程中,呼叫後端的介面變數,就需要配置成如下了:

let portUrl = "http://127.0.0.1:8001/api/";

需要注意的是:上面2個地址要一致,要麼都是127.0.0.1要 麼都是localhost,否則,還是會存在跨域問題

好的,現在應該愉快的開發了。