Service 请求服务
服务层负责处理发起的请求, 并返回对服务端的响应。
配置
/cool/config.ts
中配置请求的前缀及代理:
const host: string = "http://127.0.0.1:8001";
const baseUrl: string = (function () {
if (isDev) {
// H5模式下,可以配置代理前缀,对应 vite.config.ts 文件中 server.proxy
// #ifdef H5
return "/dev";
// #endif
// #ifndef H5
return host + "";
// #endif
} else {
// #ifdef H5
return "/api";
// #endif
// #ifndef H5
return host;
// #endif
}
})();
编辑
- 程序默认使用
eps
方式(即后端所有开放给 app 端的接口,都会在前端生成对应的方法),无需自己手动一个个添加:
注意
生成描述文件是通过 vite 插件的方式,请求 /__cool_eps
服务。所以在任意场景下,都需要运行 h5 这一端。如无法请求到接口,请替换路径: /cool/core/eps/index.ts
// /cool/config.ts
const test = {
// 是否开启
eps: true
};
- 当然也可以自己额外配置 service,在
service
目录下新建test.ts
文件:
// /service/test.ts
import { BaseService, Service } from "/@/cool";
@Service("test")
class Test extends BaseService {}
export default Test;
上面两种方式最终会合并生成 service
及描述文件
使用
引入
// 方式1
import { useCool } from "/@/cool";
const { service } = useCool();
// 方式2
import { service } from "/@/cool";
调用
// 通过方法
service.test.page().then((res) => {
console.log(res);
});
// 请求其他
service
.request({
url: "http://xxxx",
method: "GET",
data: {},
params: {}
})
.then((res) => {
console.log(res);
});
service
的结构是根据 接口路径
转化成对应的层级,打印出 service
瞅瞅。