0.0.4 • Published 5 years ago
ce-axios v0.0.4
ce-axios
安装
$ npm install ce-axios --save-dev
示例
方式1
//API声明
const API_CONFIG={
test:{
//模块配置
default:{
baseURL:'http://goods.com'
},
//接口配置,会合并模块和全局配置
api1:{
url:'/getGoodsList'
},
api2:{
url:'/test2',
method:'post',
//更多配置参考 https://github.com/axios/axios#request-config
}
}
}
//调用
import AxiosAdapter from 'ce-axios'
const api = new AxiosAdapter(null,API_CONFIG)
api.request('test.api2',参数).then(response=>{
console.log(response)
})
方式2
//instance.js
import AxiosAdapter from 'ce-axios'
import loader from './utils/loader'
class Axios extends AxiosAdapter {
constructor() {
super(...arguments)
}
//重写loader
loader() {
return loader(...arguments)
}
}
const api = new Axios()
export default api
//loader.js
function parseKey(key) {
const arr = key.split('.')
return {
name: arr.pop() || key,
path: arr.join('/')
}
}
export default function(key) {
try {
const { name, path } = parseKey(key)
const module = require(`@api/${path}`) //配置@api别名
return {
moduleConfig: module.default,
APIConfig: module[name]
}
} catch (e) {
throw new Error(e)
}
}
//res.js
import api from '../instance'
export default function () {
return api.request(...arguments).then(response => {
const { data } = response
if (data.hasOwnProperty('status')) {
const { status } = data
if (status >= 100 && status < 300) {
return data
} else {
return Promise.reject(data)
}
} else {
return response
}
})
}
//@api/test.js
export default{
default:{
baseURL:'http://goods.com'
},
//接口配置,会合并模块和全局配置
api1:{
url:'/getGoodsList'
},
api2:{
url:'/test2',
method:'post',
//更多配置参考 https://github.com/axios/axios#request-config
}
}