欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Nginx解決前端訪問資源跨域問題的方法詳解

 更新時間:2021年01月11日 11:01:17   作者:昆明--菜鳥入門  
這篇文章主要給大家介紹了關(guān)于Nginx解決前端訪問資源跨域問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

被前端跨域問題折磨快2天后,終于用ngnx的方式解決了,所以在此總結(jié)下。

該篇只探討如何用Ngnx解決跨域問題,對于原理不作討論。

1、首先介紹Windows環(huán)境下Nignx的相關(guān)命令操作

nginx常用命令:

  • 驗證配置是否正確: 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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論