一、使用步骤:
1.在config.ts中配置openAPI字段。
openAPI:数组类型,可配置多个不同模块接口。
export default defineConfig({
/**
* @name openAPI 插件的配置
* @description 基于 openapi 的规范生成serve 和mock,能减少很多样板代码
* @doc https://pro.ant.design/zh-cn/docs/openapi/
*/
openAPI: [
{
requestLibPath: "import { request } from 'umi'", // 要使用的请求库
// schemaPath: join(__dirname, 'oneapi.json'),
// schemaPath: swagger不同模块接口对应的文档路径(根据后端提供地址获取,如下截图)
schemaPath: 'http://xxx_test.com:端口号/tms-user/v2/api-docs',
projectName: 'tms-user', // 生成的api目录名(一般按模块划分)
apiPrefix: 'process.env.TMS_USER', // 接口声明文档中请求的前缀名
},
{
requestLibPath: "import { request } from 'umi'",
schemaPath: 'http://xxx_test.com:端口号/tms-waybill/v2/api-docs',
projectName: 'tms-waybill',
apiPrefix: 'process.env.TMS_WAYBILL',
},
],
define: { // 定义一些全局变量
'process.env': {
TMS_USER: '/tms-user',
TMS_WAYBILL: '/tms-waybill',
},
},
})
2.在proxy.ts中配置相关的接口请求代理(本地开发)。
可配置多个环境,如test、pre环境。-- 通过在package.json中配置不同的scripts命令来确定当前开发环境是哪个(如: npm run start:test, npm run start:pre)。
/**
* @name 代理的配置
* @see 在生产环境 代理是无法生效的,所以这里没有生产环境的配置
* -------------------------------
* The agent cannot take effect in the production environment
* so there is no configuration of the production environment
* For details, please see
* https://pro.ant.design/docs/deploy
*
* @doc https://umijs.org/docs/guides/proxy
*/
export default {
/**
* @name 详细的代理配置
* @doc https://github.com/chimurai/http-proxy-middleware
*/
test: {
'/tms-waybill': {
target: 'http://xxx_test.com:端口号', // 要代理的具体test环境接口域名
changeOrigin: true,
},
},
pre: {
'/xxx': {
target: 'your pre url', // 要代理的pre接口接口域名
changeOrigin: true,
pathRewrite: { '^': '' },
},
},
};
3.运行命令&自动生成接口文档目录。
运行命令:npm run openapi -》 系统会自动在src/services目录下自动生成接口模块目录&不同api文件 -》再运行 npm run start:test -》在页面中开始调用接口即可。
4.页面中使用接口即可。
// xxx.tsx页面
import api from '@/services/tms-waybill'
const getList = async (params: object) => {
const { data } = await api.ProjectManageController.getListUsingPOST({ ...params });
console.log('后台返回的是', data);
};
二、常见问题&解决
1. 使用命令npm run openapi生成最新的接口文档时,vscode控制台报错:can't read version property value of undefind,xxx。
答:因后台接口正在上传代码(发版),待发版后,再重新运行npm run openapi命令即可。