簡介
-
這裏靜態資源就以之前的一個項目文章地址爲例,源碼 Github,項目本身很簡單,只是分別對第三方的服務端、自己的服務端發起請求。
-
不論是調用第三方服務端接口,還是自己的後端服務,如果跨域未在服務器端處理,那麼 Vue 部署時需要在生產環境下處理跨域。下面以 Windows 爲例,採用 Nginx 兩個步驟,來實現針對 Vue 項目的靜態資源服務器及跨域配置。
Notes: 補充一下,何爲跨域?借用安全大神吳翰清名作《白帽子講Web安全》中的一張圖:
即,但凡協議、主機、端口
中的任一個不同,該請求便爲跨域操作。
效果
第一步 通過 Nginx 搭建靜態資源服務器
-
vue-cli
搭建的項目通過npm run build
進行構建,完成生產環境下的打包,生成dist
靜態資源目錄,eg:E:/dist
。 -
編輯 Nginx 配置文件,在 nginx.conf 文件中新增
server
節點如下(主要是root
的路徑指向打包後的目錄)
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root E:/dist;
index index.html index.htm;
}
}
Notes:
- Linux 下 Nginx 配置文件的默認路徑:
/etc/nginx/nginx.conf
,通過vi /etc/nginx/nginx.conf
修改。 - 實際項目中
server_name
一般採用域名,這裏在本機測試,設置爲localhost。
至此,靜態資源服務器已搭建完畢,nginx -s reload
刷新 Nginx 配置;在瀏覽器訪問對應的地址+端口,不出意外,應該可以正常訪問到 Vue 的前端頁面。然而,問題是,這些接口由於需要跨域都不能正常調用(╥╯^╰╥)。
第二步 在 Nginx 中完成跨域配置
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root E:/dist;
index index.html index.htm;
}
# Solve the CORS problem
location /3rd { # custom prefix: third party API
rewrite ^/3rd/(.*)$ /$1 break; # rewrite the URL and redirect
include uwsgi_params;
proxy_pass http://www.tuling123.com/openapi/api; # Third party API URL
}
location /api { # custom prefix
include uwsgi_params;
proxy_pass http://your-server-ip:port; # Server side API URL
}
}
Notes: Vue開發環境跨域
至此,便實現了基於Nginx的靜態資源服務器及跨域配置,後續將從實例出發,逐步介紹Nginx反向代理
,Nginx負載均衡
。
Source Code: Github
If you have any questions or any bugs are found, please feel free to contact me.
Your comments and suggestions are welcome!