終於解決了困擾了兩天的問題:
需求:
基於vue3的前端專案以及基於laravel的後端專案。將他們分別配置為127.0.0.1 www.ggzx.com 以及 127.0.0.1 www.zx.com。
再在nginx上配置相應的專案,如下:
前端專案:
後端專案:
問題:
由於兩個專案的前後端是不同的源,因此在瀏覽器中會有跨域的問題。
解決辦法需要兩個步驟:①服務端需要在Nginx配置中為你的代理服務新增正確的CORS頭部設定 ②伺服器設定中介軟體允許固定的訪問源進行訪問
如下:
server { listen 8000; server_name www.zx.com; root /Users/hoge/Desktop/code/php/zxAdmin/public; index index.php index.html index.htm; # 處理 API 路由的 CORS 配置 location / { proxy_pass http://www.ggzx.com; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # 新增CORS頭部 add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,token'; # 預檢請求響應,nginx會傳送兩個請求,其中先傳送預處理請求,當允許訪問的時候再傳送真正的請求 if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,token'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain charset=UTF-8'; add_header 'Content-Length' 0; return 204; } try_files $uri $uri/ /index.php?$query_string; } # 處理 PHP 檔案 location ~ \.php$ { include fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } # 禁止訪問 .ht 檔案 location ~ /\.ht { deny all; } # 靜態檔案快取 location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires max; log_not_found off; } }
②設定中介軟體檔案
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class HandleCors { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse */ public function handle(Request $request, Closure $next) { $response = $next($request); // 設定跨域 $response->headers->set('Access-Control-Allow-Origin', '*'); $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Origin, X-CSRF-Token'); return $response; } }
在介面呼叫前使用中間建