天天看點

vue/react項目中使用proxy代理處理跨域問題

vue/react項目中使用proxy代理處理跨域問題

最近在項目更新疊代中遇到需要設定代理來通路伺服器的問題,跟大家分享下!(剛好是兩個架構的項目并行開發…)

proxy:本地的網站請求的資料會通過我們的伺服器進行代理,由伺服器發送真實的資料請求到目标資料背景 ! 浏覽器有同源政策,但是伺服器沒有.

1.vue項目中一般在config\index.js下dev或者vue.comfig.js的proxyTable配置,

react項目一般在webpack.config.js中devServer裡來配置proxy。

devServer.proxy 可以是一個指向開發環境 API 伺服器的字元串

```c
//	預設伺服器會将任何未知請求 (沒有比對到靜态檔案的請求) 代理到http://localhost:4000上
module.exports = {
  devServer: {
    proxy: '代理位址'
  }
}
           

2.(配置proxy)代碼示例

proxy: {
        '/mobile': { 
        // proxy的key表示比對以這個字段開頭的請求
        target: "代理位址", 
        // 配置需要跨域的IP(域名)位址/通路目标位址
        secure: false,  // 如果是https此處改為true
       	ws: true,  // 如果要代理 websockets,才配置這個參數
        changeOrigin: true, // 是否跨域,true為允許跨域
        pathRewrite: { '^/mobile': '/mobile' },
        // 代表重寫,前邊的是比對規則,後邊是重寫本地發起的路徑,
        // 如果target中包含了key值/mobile,則{ '^/mobile': '/' },。
      }
},
           

proxy裡面可寫多個key值來比對更多的位址

proxy: {
      '/mobile': {
        target: '代理位址',
        secure: false,
        changeOrigin: true,
        pathRewrite: { '^/mobile': '/mobile' },
      },
      "/api": {
        target: "代理位址",
        changeOrigin: true,
        pathRewrite: { "^/api": "/" },
      },
      '/': {
  			target: '代理位址',
  			changeOrigin: true,
 			pathRewrite: {},
	  },
    },
           

一般這樣代理就配置好了,記得重新開機項目!如設定了多個代理,有的未生效,可以百度下 proxy的比對規則。

解決跨域方法不止一種,選擇适合的即可

------	希望能夠幫助大家,感謝大家圍觀閱讀	------