不需要重启项目,就能快速切换api接口的访问环境,通过改变URL前缀访问不同的接口环境

209 阅读1分钟

背景

码农一天的开发日常:

  1. 业务开发:停止Ctrl+c,启动npm run dev,开发中...
  2. 解决测试环境问题:停止Ctrl+c,启动npm run test,调试...
  3. Java张三:停止Ctrl+c,启动npm run zhangsan,联调...
  4. Java李四:停止Ctrl+c,启动npm run lisi,联调...
  5. Uat环境问题:停止Ctrl+c,启动npm run uat,调试中...
  6. 。。。。

面对多个环境多个后端业务对接的情况,每次对接不一样的业务需求都需要重新启动项目,非常的浪费时间。

通过URL快速切换环境

我们可以通过url的访问路由前缀来确定当前的访问环境,效果如下:

默认访问环境:http://localhost:8080/home  // 默认访问环境问 dev
开发环境:http://localhost:8080/dev/home
测试环境:http://localhost:8080/test/home
UAT环境:http://localhost:8080/uat/home
xx同事本地:http://localhost:8080/xx/home

修改webpack代理配置

将所有的环境都配置到webpack的devServer proxy

const prefix = '/api/'
const apiProxy = {
    dev: 'https://dev.domain.com',
    test: 'http://test.domain.cn',
    uat: 'https://uat.domain.com',
    zhangsan: 'https://192.168.100.10:4088',
    lisi: 'https://192.168.100.86:8894',
}

// 设置默认的代理  =====> 默认访问环境:http://localhost:8080/home  // 默认访问环境问 dev
const proxy = {
    [`/${prefix}`]: {
        // 独立客户端请求代理配置
        target: apiProxy.dev + '/' + prefix,
        pathRewrite: { [`^/${prefix}`]: '' },
    },
}
Object.keys(apiProxy).map((key) => {
    const proxyUrl = apiProxy[key]
    proxy[`/${key}/${prefix}`] = {
        target: proxyUrl + `/${prefix}`,
        pathRewrite: { [`^/${key}/${prefix}`]: '' },
    }
})

// webpack 的 devServer 代理配置
config.devServer = {
    proxy,
    ...
}

修改项目中的路由问题路径

由于项目启动后的访问地址增加了前缀,所以项目的路由需要相应的配置访问前缀,以 react-router 为例

// index.js
import { BrowserRouter } from 'react-router-dom'

// 根据 location.href 获取当前的访问环境(http://localhost:8080/test/home)
const envType = getEnvType() // envType = 'test'

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
root.render(
    <React.StrictMode>
        <BrowserRouter basename={envType}>
            <App />
        </BrowserRouter>
    </React.StrictMode>
)

这样就能够通过URL快速的切换访问环境了。