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上的一级域名