快速开始
安装
使用npm或yarn安装awe-axios:
bash
# 使用npm
npm install awe-axios --save
# 使用yarn
yarn add awe-axios环境要求
由于awe-axios大量采用了装饰器语法,所以需要使用TypeScript进行开发。你必须要在你的项目中安装TypeScript环境,并为tsconfig.json添加以下配置:
json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}基本使用
typescript
@HttpApi({
baseURL: 'http://localhost:3000/users',
})
class UserApi {
// 等价于 axios.get('http://localhost:3000/users')
@Get('/')
getAllUsers(): any {}
// 等价于 axios.get(`http://localhost:3000/users/${id}`)
// 失败时请求重发次数为3
@Get({
url: '/:id',
retry: 3,
})
getUserById(@PathParam('id') id: number): any {}
// 允许请求体参数
@Post('/')
addUser(@BodyParam() data: { name: string; age: number }): any {}
// 允许定义为mock接口
@Get({
url: '/page',
mock: {
handlers: () => {
return HttpResponse.json({
data: [1, 2, 3],
total: 3,
});
},
},
})
getPage(@QueryParam('page') page: number, @QueryParam('size') size: number): any {}
}使用原生 axios
如果你需要使用原生axios库,你可以直接导入axiosPlus,然后像使用axios一样使用axiosPlus,下面是一个拦截器的案例:
typescript
import { axiosPlus } from 'awe-axios';
axiosPlus.interceptors.request.use(config => {
console.log('请求拦截器', config);
return config;
});