Umi 使用Proxy

umi代理只能代理本http://localhost:xxx

如果项目在app.tsx中配置

// 配置request
export const request: RequestConfig = {
  ...
  prefix: RequestHOST,
};

RequestHOST一般会配置在config目录,然后通过config.dev.ts、config.test.ts、config.prod.ts

//config.dev.ts
import { defineConfig } from 'umi';

export default defineConfig({
  ...
  define: {
    'process.env.UMI_ENV': 'dev',
    RequestHOST: 'https://demo/gateway',
  },
});

这样我们本地请求接口的前缀就是成了RequestHOST,而不是localhost。

但是umi只能代理localhost的请求,所以需要把RequestConfig配置中的prefix删除来本地调试。

  '/demo': {
      // 要代理的地址
      target: 'https://xxxx/XXXX/aaa',
      // 配置了这个可以从 http 代理到 https
      // 依赖 origin 的功能可能需要这个,比如 cookie
      changeOrigin: true,
      pathRewrite: {
        '^/demo': '/demo',
      },
    },
 '/api': {
    'target': 'http://jsonplaceholder.typicode.com/',
    'changeOrigin': true,
    'pathRewrite': { '^/api' : '' },
  }

然后访问 /api/users 就能访问到 http://jsonplaceholder.typicode.com/users 的数据。

'pathRewrite': { '^/api' : '' },就是把请求路径上的api替换为空,如果是

'/api': {
    'target': 'http://jsonplaceholder.typicode.com/',
    'changeOrigin': true,
    'pathRewrite': { '^/api' : '/api' },
  }

那么访问的就是http://jsonplaceholder.typicode.com/api/users。

注意proxy的代理到https不能在iframe中生效。

代理其他域名 ,比如我的接口请求是:https://demo/haha 。

不能直接代理 https://demo/haha,只能代理http://localhost:8100/haha,然后再配置proxy转发到后端本地。

我们也可以让网关配置cors,把源是http://localhost的所有端口都放开也可以解决跨域问题。

针对单个接口

  '/gateway/aaa/bbb/ccc/ddd': {
      target: 'http://10.123.5.75:8081',
      changeOrigin: true,
      pathRewrite: {
        '^/gateway/aaa/bbb/ccc/ddd': '/bbb/ccc/ddd',
      },
    },

如果没有在RequestConfig配置里面配置prefix,那么umi默认使用当前url上的一级域名

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值