Nginx解決前端訪問資源跨域問題的方法詳解
被前端跨域問題折磨快2天后,終于用ngnx的方式解決了,所以在此總結(jié)下。
該篇只探討如何用Ngnx解決跨域問題,對于原理不作討論。
1、首先介紹Windows環(huán)境下Nignx的相關(guān)命令操作
nginx常用命令:
- 驗(yàn)證配置是否正確: nginx -t
- 查看Nginx的版本號:nginx -V
- 啟動Nginx:start nginx
- 快速停止或關(guān)閉Nginx:nginx -s stop
- 正常停止或關(guān)閉Nginx:nginx -s quit
- 配置文件修改重裝載命令:nginx -s reload
在停止ngix后,會自動刪除/logs目錄下的nginx.pid
- 可以使用命令nginx -c conf/nginx.conf 重新創(chuàng)建 或者 再次啟動nginx
查看nignx 監(jiān)聽端口 是否啟動成功
- netstat -ano | findstr 端口號
解決關(guān)閉nignx后 端口仍在監(jiān)聽中
1、netstat -ano | findstr 端口號 #獲取到PID
2、tasklist | findstr "PID" #命令找到nginx進(jìn)程信息
3、taskkill /f /t /im nginx.exe #結(jié)束nginx進(jìn)程
2、介紹如何配置Nignx 解決跨域問題
前端ip端口號:http://localhost:8080/
后端ip端口號:http://localhost:8082/
現(xiàn)在我們在不做跨域設(shè)置時,前端請求如下
uni.request({ url:'http://localhost:8082/ApiController/test', success:(res)=>{ console.log(res.data) }, })
訪問地址:'http://localhost:8082/ApiController/test',就會出現(xiàn)
那么我們進(jìn)行Nignx配置
編輯 /config/nginx.conf此文件
1)添加頭信息,在nginx.conf配置文件http塊中添加跨域訪問配置
add_header Access-Control-Allow-Origin *; //允許所有域名跨域訪問代理地址 add_header Access-Control-Allow-Headers X-Requested-With; add_header Access-Control-Allow-Methods GET; //跨域請求訪問請求方式,
2)設(shè)置反向代理
server { listen 80; #配置nignx的監(jiān)聽端口 server_name localhost; #配置nignx的監(jiān)聽地址 location /ApiController{ #監(jiān)聽地址 以/ApiController開頭的地址 proxy_pass http://localhost:8082; #轉(zhuǎn)發(fā)地址 } }
此時配置后我們前端訪問url
http://localhost:8082/ApiController/test 應(yīng)修改為http://localhost:80/ApiController/test
#此時監(jiān)聽
以localhost為域名
以80為端口
以/ApiController為地址開頭
才會進(jìn)行地址轉(zhuǎn)發(fā)
uni.request({ url:'http://localhost:80/ApiController/test', success:(res)=>{ console.log(res.data) }, })
結(jié)果:(訪問成功)
總結(jié)
到此這篇關(guān)于Nginx解決前端訪問資源跨域問題的文章就介紹到這了,更多相關(guān)Nginx解決前端訪問資源跨域內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。