利用nginx解決vue的跨域訪問問題
阿新 • • 發佈:2018-12-12
vue在開發中,可以通過自帶的腳手架配置實現跨域訪問,但是打包時不會將這部分配置檔案載入,這樣會導致上了生產環境出現跨域訪問的問題。在網上查過一些解決跨域的問題,都沒太搞明白,然後就想採用nginx將服務請求轉發來實現,經過一天的摸索,終於搞定了。
最開始的的nginx配置如下:
server { listen 80; server_name abc.def.com; index index.html; location / { root /usr/share/nginx/html/app; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
這個配置是將所有訪問“abc.def.com”的請求都轉發到對應的路徑下,然後請求服務的連結為:http://w.xyz.com/projectname/rs/service/servicename(採用resteasy開發的Java服務),就會產生跨域問題。
之前解決過一次跨域問題,就是將vue的程式碼放到java工程的WwbRoot目錄下,請求連結將字首去掉,改為:/projectname/rs/servicename,這樣因為成了本地請求,就避免了跨域訪問。
然後基於以上兩點,將nginx進行改造,如下:
server { listen 80; server_name abc.def.com; index index.html; location ~ (/static/|index.html) { root /usr/share/nginx/html/app; } location ~ /projectname/ { proxy_pass http://w.xyz.com; } #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; } }
將之前的location進行改造,規定只有訪問字首是/static/或者index.html這兩種情況,才會轉發到本地的vue目錄下,保證了前端可以正常訪問頁面。
然後新增一個location,規定/projectname/開頭的的請求,會被轉發到http://w.xyz.com這個地址。
這樣就實現了vue的跨域訪問了。