被前端跨域問題折磨快2天后,終于用ngnx的方式解決了,所以在此總結(jié)下。
該篇只探討如何用Ngnx解決跨域問題,對(duì)于原理不作討論。
1、首先介紹Windows環(huán)境下Nignx的相關(guān)命令操作
nginx常用命令:
- 驗(yàn)證配置是否正確: nginx -t
- 查看Nginx的版本號(hào):nginx -V
- 啟動(dòng)Nginx:start nginx
- 快速停止或關(guān)閉Nginx:nginx -s stop
- 正常停止或關(guān)閉Nginx:nginx -s quit
- 配置文件修改重裝載命令:nginx -s reload
在停止ngix后,會(huì)自動(dòng)刪除/logs目錄下的nginx.pid
- 可以使用命令nginx -c conf/nginx.conf 重新創(chuàng)建 或者 再次啟動(dòng)nginx
查看nignx 監(jiān)聽端口 是否啟動(dòng)成功
- netstat -ano | findstr 端口號(hào)
解決關(guān)閉nignx后 端口仍在監(jiān)聽中
1、netstat -ano | findstr 端口號(hào) #獲取到PID
2、tasklist | findstr "PID" #命令找到nginx進(jìn)程信息
3、taskkill /f /t /im nginx.exe #結(jié)束nginx進(jìn)程
2、介紹如何配置Nignx 解決跨域問題
前端ip端口號(hào):http://localhost:8080/
后端ip端口號(hào):http://localhost:8082/
現(xiàn)在我們?cè)诓蛔隹缬蛟O(shè)置時(shí),前端請(qǐng)求如下
uni.request({
url:'http://localhost:8082/ApiController/test',
success:(res)=>{
console.log(res.data)
},
})
訪問地址:'http://localhost:8082/ApiController/test',就會(huì)出現(xiàn)
![](/d/20211016/4f56bfafd5f1727b4c94d41af76cd268.gif)
那么我們進(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; //跨域請(qǐng)求訪問請(qǐng)求方式,
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ā)地址
}
}
此時(shí)配置后我們前端訪問url
http://localhost:8082/ApiController/test 應(yīng)修改為http://localhost:80/ApiController/test
#此時(shí)監(jiān)聽
以localhost為域名
以80為端口
以/ApiController為地址開頭
才會(huì)進(jìn)行地址轉(zhuǎn)發(fā)
uni.request({
url:'http://localhost:80/ApiController/test',
success:(res)=>{
console.log(res.data)
},
})
結(jié)果:(訪問成功)
![](/d/20211016/5dc8f07d451576cbd0a7360012a87922.gif)
總結(jié)
到此這篇關(guān)于Nginx解決前端訪問資源跨域問題的文章就介紹到這了,更多相關(guān)Nginx解決前端訪問資源跨域內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!