首頁 > 運維 > Nginx > 主體

nginx跨域問題如何解決

WBOY
發布: 2023-05-13 23:43:04
轉載
5281 人瀏覽過

前後端分離,使用nginx解決跨域問題

前端:vue.js nodejs webpack

後台:springboot

反向代理伺服器:nginx

想法:將前端程式碼打包,讓nginx指向靜態資源,nginx對後台請求進行轉送。

1、將前端程式碼打包:

npm run build
登入後複製

會產生一個dist資料夾。包含一個index.html檔案和一個static資料夾,路徑以我本機為例:

/users/xxx/ideaprojects/webtest/dist

2、開啟

/usr/local/etc/nginx目錄下的nginx.conf,在server中加入如下:

listen  80; #原为8080,避免冲突,更改为80

  server_name localhost;

 

  #charset koi8-r;

 

  #access_log logs/host.access.log main;

 

 

  location / {

   root /users/xxx/ideaprojects/webtest/dist;

   index index.html;

    

   # 此处用于处理 vue、angular、react 使用h5 的 history时 重写的问题

   if (!-e $request_filename) {

    rewrite ^(.*) /index.html last;

    break;

   }

  }

 

 

  # 代理服务端接口

  location /api/ {

   proxy_pass http://localhost:8080/;# 代理接口地址

  }
登入後複製

測試

##前端發送請求:http://localhost/test ,vue-router將其重定向為http://localhost/api/demo/1,實際存取是http://localhost:8080/demo/1。

直接向後台發送請求:訪問http://localhost/api/demo/1,實際訪問是:http://localhost:8080/demo/1

內容擴充思考:


1).

# 代理程式服務端介面

location /api/ {
proxy_pass http://localhost:8080/;# 代理接口地址
}
登入後複製

代理程式介面位址只到8080,那麼他會自動將後台專案的名稱加上? ? ?例如介面是http://148.70.110.87:8080/專案名稱/方法名稱 。 。 。

2).js 中是這樣請求的,nginx是按照您上面的配置,但是請求出錯http://148.70.110.87/api/index2 404 (not found)

axios.post('/api/index2')
.then( (response) =>{
console.log(response);
})
.catch( (error)=> {
console.log(error);
});
登入後複製
3).第三個步驟,測試,實在看不懂要是能有相關的程式碼就好了

以上是nginx跨域問題如何解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:yisu.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!