被前端跨域問題折磨快2天后,終于用ngnx的方式解決了,所以在此總結下。
該篇只探討如何用Ngnx解決跨域問題,對于原理不作討論。
1、首先介紹Windows環境下Nignx的相關命令操作
nginx常用命令:
- 驗證配置是否正確: nginx -t
- 查看Nginx的版本號:nginx -V
- 啟動Nginx:start nginx
- 快速停止或關閉Nginx:nginx -s stop
- 正常停止或關閉Nginx:nginx -s quit
- 配置文件修改重裝載命令:nginx -s reload
在停止ngix后,會自動刪除/logs目錄下的nginx.pid
- 可以使用命令nginx -c conf/nginx.conf 重新創建 或者 再次啟動nginx
查看nignx 監聽端口 是否啟動成功
- netstat -ano | findstr 端口號
解決關閉nignx后 端口仍在監聽中
1、netstat -ano | findstr 端口號 #獲取到PID
2、tasklist | findstr "PID" #命令找到nginx進程信息
3、taskkill /f /t /im nginx.exe #結束nginx進程
2、介紹如何配置Nignx 解決跨域問題
前端ip端口號:http://localhost:8080/
后端ip端口號:http://localhost:8082/
現在我們在不做跨域設置時,前端請求如下
1
2
3
4
5
6
|
uni.request({ url: 'http://localhost:8082/ApiController/test' , success:(res)=>{ console.log(res.data) }, }) |
訪問地址:'http://localhost:8082/ApiController/test',就會出現
那么我們進行Nignx配置
編輯 /config/nginx.conf此文件
1)添加頭信息,在nginx.conf配置文件http塊中添加跨域訪問配置
1
2
3
|
add_header Access-Control-Allow-Origin *; // 允許所有域名跨域訪問代理地址 add_header Access-Control-Allow-Headers X-Requested-With; add_header Access-Control-Allow-Methods GET; // 跨域請求訪問請求方式, |
2)設置反向代理
1
2
3
4
5
6
7
|
server { listen 80; #配置nignx的監聽端口 server_name localhost; #配置nignx的監聽地址 location /ApiController { #監聽地址 以/ApiController開頭的地址 proxy_pass http: //localhost :8082; #轉發地址 } } |
此時配置后我們前端訪問url
http://localhost:8082/ApiController/test 應修改為http://localhost:80/ApiController/test
#此時監聽
以localhost為域名
以80為端口
以/ApiController為地址開頭
才會進行地址轉發
1
2
3
4
5
6
|
uni.request({ url: 'http://localhost:80/ApiController/test' , success:(res)=>{ console.log(res.data) }, }) |
結果:(訪問成功)
總結
到此這篇關于Nginx解決前端訪問資源跨域問題的文章就介紹到這了,更多相關Nginx解決前端訪問資源跨域內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/kunming97/p/14257585.html