在uni內使用代理解決跨域


使用uniapp 進行調試對接時有時候會遇到跨域問題;嘗試使用ngnix代理服務后,發現uni編譯后,訪問時存在編碼等問題,解決起來比較麻煩,所以找到了uni自帶的代理服務。

在uni根目錄下manifest.json中切換到源碼視圖,然后在根節點下添加以下代碼

  "h5" : {
        "devServer" : {
            "port" : 8083,
            "disableHostCheck" : true,
            "proxy" : {
                "/api" : {
                    "target" : "http://47.92.113.152:7583",
                    "changeOrigin" : true,
                    "secure" : false,
                    "pathRewrite" : {
                        "^/api" : "/umcp"
                    }
                },
                "/file" : {
                    "target" : "http://47.92.113.152:7580",
                    "changeOrigin" : true,
                    "secure" : false,
                    "pathRewrite" : {
                        "^/file" : "/rygl"
                    }
                }
            }
        }
    }

配置修改后需要重啟服務。

當上方代理設置完成后,請求路徑的寫法

  sServer = '/api/'; // 反向代理
reqUrl=sServer+'
sso/user/get';//接口路徑
    // 瀏覽器會將reqUrl轉換為http://localhost:8083/api/sso/user/get

這樣當我們進行請求時

瀏覽器會將

http://localhost:8083/api/
其中'
http://localhost:8083'解析成配置項的 proxy中對應'/api'模塊的traget路徑'http://47.92.113.152:7583'

將代理模塊'/api' 通過配置項中設置的pathRewrite,覆寫為'/umcp'
 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM