React動態切換本地代理地址(devServer.proxy)


背景需求

在本地跑React項目時,調用的接口往往是跨域的,一般常用的是webpack-dev-server提供的prxoy代理功能。然而在每次切換代理環境后,都需要重新跑項目,對於開發人員來說太麻煩了。如果能夠在切換代理環境后,不用重跑項目,豈不是提升了開發體驗和減少了項目編譯的時間呢?

● webpack.devServer.config.js


'use strict';
const fs = require('fs');
// ...
module.exports = function(proxy, allowedHost) {
    return {
        // ...
        proxy: {
          '/test': {
              target: 'http://192.168.xx.xx:8001',
              changeOrigin: true,
          },
          '/user': {
              target: 'http://192.168.xx.xx:8002',
              changeOrigin: true,
          },
        },
    };
};

需求分析

根據項目的背景需求,分析了一下原因,之所以需要重跑項目,是因為修改配置后,webpack不會重新讀取我們修改后的代理配置文件(webpack.devServer.config.js)。

那么,這么一分析下來話,想要解決這個問題,有兩種思路:

  1. 讓webpack監聽我們代理的配置文件(webpack.devServer.config.js),一旦文件有修改就重新熱加載;
  2. 讓webpack實時讀取配置文件中的proxy配置,能夠在每次代理的時候實時讀取,不用每次重新加載。

基於這兩種思路,我去查閱了下webpack的官方文檔。

查閱文檔

devServer.proxy

在查閱了webpack官網中devServer.proxy的內容后,發現這個devServer是用了http-proxy-middleware包去實現的,並且給出了它的官方文檔

devs-server-proxy-01.png

http-proxy-middleware

http-proxy-middleware中發現了這樣一個router配置參數,意思是可以針對特殊的一些請求重新定位/代理

  • option.router: object/function, re-target option.target for specific requests.
// Use `host` and/or `path` to match requests. First match will be used.
// The order of the configuration matters.
router: {
  'integration.localhost:3000' : 'http://localhost:8001',  // host only
  'staging.localhost:3000'     : 'http://localhost:8002',  // host only
  'localhost:3000/api'         : 'http://localhost:8003',  // host + path
  '/rest'                      : 'http://localhost:8004'   // path only
}

// Custom router function (string target)
router: function(req) {
  return 'http://localhost:8004';
}

// Custom router function (target object)
router: function(req) {
  return {
    protocol: 'https:', // The : is required
    host: 'localhost',
    port: 8004
  };
}

// Asynchronous router function which returns promise
router: async function(req) {
  const url = await doSomeIO();
  return url;
}

其中router可以傳遞函數並且支持async函數,那么意味着,是不是webpack能夠實時讀取proxy的配置呢。

驗證想法

為了驗證這個API,我先搭建了兩個node服務,再通過配置webpack.devServer.config.js中的proxy中動態的請求代理地址參數去驗證想法。

服務端口8001

如下,搭建端口為8001的node服務有以下功能:

  • /getRouterProxyUrl隨機返回80018002端口的代理地址,
  • /test,返回8001 succesed get test word!
const http = require('http');
const server8001 = http.createServer(function(req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-type,Content-Length,Authorization,Accept,X-Requested-Width");
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");

    let proxyUrl = '';

    if (req.url == "/getRouterProxyUrl") {
        if (Math.random() * 10 > 5) {
            proxyUrl = 'http://192.168.xx.xx:8001';
        } else {
            proxyUrl = 'http://192.168.xx.xx:8002';
        }
        res.writeHead(200, {
            'Content-type': 'text/plain;charset=UTF8',
        });
        res.end(proxyUrl);
    } else if (req.url == "/test") {
        res.writeHead(200, { 'Content-type': 'text/plain;charset=UTF8' });
        res.end('8001 succesed get test word!');
    } else {
        res.writeHead(200, { 'Content-type': 'text/plain;charset=UTF8' });
        res.end(`8001 hello,your request url is ${req.url}`);
    }
    console.debug(new Date(), `8001 req.url:${req.url}`);
    console.debug(new Date(), `8001 proxyUrl:${proxyUrl}`);
});

server8001.listen('8001', function() {
    console.log((new Date()) + 'Server is listening on port:', 8001);
})

服務端口8002

如下,端口為8002的node服務有以下功能:

  • /test返回8002 succesed get test word!
const http = require('http');

const server8002 = http.createServer(function(req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-type,Content-Length,Authorization,Accept,X-Requested-Width");
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");

    if (req.url == "/test") {
        res.writeHead(200, { 'Content-type': 'text/plain;charset=UTF8' });
        res.end('8002 succesed get test word!');
    } else {
        res.writeHead(200, { 'Content-type': 'text/plain;charset=UTF8' });
        res.end(`8002 hello,your request url is ${req.url}`);
    }
    console.debug(new Date(), `8002 req.url:${req.url}`);

});

server8002.listen('8002', function() {
    console.log((new Date()) + 'Server is listening on port:', 8002);
})

配置proxy

webpack.devServer.config.js文件如下,通過getFecth去請求動態的代理地址,router中拿到getFecth中請求到的代理地址再返回

'use strict';
const fs = require('fs');
const http = require('http');
// ...
const getFetch = () => {
    return new Promise((resolve, reject) => {
        http.get('http://192.168.xx.xx:8001/getRouterProxyUrl', res => {
            let todo = '';
            res.on('data', chunk => {
                todo += chunk;
            });
            res.on('end', () => {
                resolve(todo);
            });
            res.on('error', (error) => {
                reject(error);
            });
        });
    });
};

module.exports = function(proxy, allowedHost) {
    return {
        // ...
       proxy: {
          '/test': {
              target: 'http://localhost:3000',
              changeOrigin: true,
              router: async function() {
                  const url = await getFetch();
                  return url;
              },
          },
      }
    };
};

前端請求

fetch('/test')
  .then(response => {
    if (!response.ok) {
      throw 'Error';
    }
    return response.text();
  })
  .then(res => console.debug(res))
  .catch(err => console.error(err));

請求報錯500 Internal Server Error

前端請求后,發現報了500 Internal Server Error 的錯誤

devs-server-proxy-02.png

為了排除服務端的錯誤,使用postman對8001端口的/getRouterProxyUrl/test,還有8002端口的/test,均發起請求驗證了下,都能正常返回正常的響應數據!

devs-server-proxy-03.png

這就很納悶,可能還是在router代理地址這里除了問題,但是通過打console.log,發現getFetch是能正常返回數據的。再根據錯誤提示,可以大致判斷是在router里邊調用接口導致出錯的。

TypeError: Cannot read property 'split' of undefined
    at required (D:\workspace\Web\react-app\node_modules\requires-port\index.js:13:23)
    at Object.common.setupOutgoing (D:\workspace\Web\react-app\node_modules\http-proxy\lib\http-proxy\common.js:101:7)
    at Array.stream (D:\workspace\Web\react-app\node_modules\http-proxy\lib\http-proxy\passes\web-incoming.js:127:14)
    at ProxyServer.<anonymous> (D:\workspace\Web\react-app\node_modules\http-proxy\lib\http-proxy\index.js:81:21)
    at middleware (D:\workspace\Web\react-app\node_modules\http-proxy-middleware\lib\index.js:46:13)
    at handle (D:\workspace\Web\react-app\node_modules\webpack-dev-server\lib\Server.js:322:18)
    at D:\workspace\Web\react-app\node_modules\webpack-dev-server\lib\Server.js:330:47
    at Layer.handle_error (D:\workspace\Web\react-app\node_modules\express\lib\router\layer.js:71:5)
    at trim_prefix (D:\workspace\Web\react-app\node_modules\express\lib\router\index.js:315:13)
    at D:\workspace\Web\react-app\node_modules\express\lib\router\index.js:284:7

再回到http-proxy-middleware的官方文檔

  • option.router: object/function, re-target option.target for specific requests.
// Asynchronous router function which returns promise
router: async function(req) {
    const url = await doSomeIO();
    return url;
}

這里 await doSomeIO()引起了我的注意,這個函數命名是不是意味着這里異步的路由函數只能是做一些I/O操作,並不支持調用接口呢?抱着這個疑問,我再查了下資料

devs-server-proxy-04.png

有沒有可能是router返回的參數不正確,異步函數中不應該是返回string字符串。
於是代碼改為如下,在router函數中調用異步接口,測試后是不報錯的。

router: function() {
    getFetch();
    return {
        protocol: 'http:', // The : is required
        host: '192.168.xx.xx',
        port: 8001,
    };
},

然后再把router改為異步函數,在里邊調用getFetch,測試后是報錯的!難道router不支持異步函數???離離原上譜!

router: async function() {
    getFetch();
    return {
        protocol: 'http:', // The : is required
        host: '192.168.xx.xx',
        port: 8001,
    };
},

http-proxy-middleware版本問題

我再去查了下資料https://github.com/chimurai/http-proxy-middleware/issues/153

devs-server-proxy-05.png

發現http-proxy-middleware是在0.21.0版本才支持async router,那么我們再檢查下webpack中webpack-dev-server的版本

devs-server-proxy-06.png

好家伙,webpack-dev-server里邊引用的http-proxy-middleware中間件是0.19.1版本,我說試了半天咋沒有用。那這個async router在咱們項目里就不能用了,要用還得升級下中間件的版本。

支持I/O操作

正當想放棄的時候,剛剛中間件文檔提到的router一個用法async doSomeIO,要不試試I/O操作,看下在router里邊調用文件流能否成功。

  • test.env.json
{
  "protocol": "http:",
  "host": "192.168.xx.xx",
  "port": 8002
}
  • proxy
'/test': {
    target: 'http://192.168.xx.xx:8001',
    changeOrigin: true,
    router: function() {
        const envStr = fs.readFileSync('./test.env.json', 'utf-8');
        const { protocol, host, port } = JSON.parse(envStr);
        return {
            protocol,
            host,
            port,
        };
    },
}

在頁面里點擊調用fetch("/test"),發現請求通了,並且是從端口為8002的服務器返回的結果!

devs-server-proxy-07.png

果然可以做I/O操作,那如果在不重啟項目的情況下,修改test.env.json的代理配置,把port改為8001,再繼續調用fetch("/test"),請求的結果會變成8001端口服務器返回的嗎?

{
  "protocol": "http:",
  "host": "192.168.xx.xx",
  "port": 8001
}

修改完test.env.json的配置后,繼續調用fetch("/test"),發現請求的結果變成了8001端口服務器返回的了!

devs-server-proxy-08.png

到這一步,就驗證了咱們最初的想法——“希望能夠在修改代理環境后,不用重新跑項目即可”,是可行的!

實現代碼

  • test.env.json
{
  "protocol": "http:",
  "host": "192.168.xx.xx",
  "port": 8001
}
  • webpack.devServer.config.js
'use strict';
const fs = require('fs');
// ...
const getEvnFilesJSON = (context) =>{
  // const = {req,url,methods } = context;
  // ...可根據req,url,methods來獲取不同的代理環境
  const envStr = fs.readFileSync('./test.env.json, 'utf-8');
  const { protocol, host, port } = JSON.parse(envStr);
  return { protocol, host, port } 
};

module.exports = function(proxy, allowedHost) {
    return {
        // ...
        proxy: {
            '/test': {
                target: 'http://192.168.xx.xx:8001',
                changeOrigin: true,
                router: getEvnFilesJSON
            },
        },
    };
};

總結

  1. webpack的web-dev-server是基於http-proxy-middleware實現的
  2. http-proxy-middleware中 options.routerasync router功能是在0.21.0版本開始支持的
  3. http-proxy-middleware中options.router功能支持I/O操作

后續有時間可以用Electron開發一個管理React本地devServer.Proxy的工具!像SwitchHosts一樣!

鏈接


免責聲明!

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



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