写在前面
我们都知道,前端和后端沟通的桥梁是ajax请求接口,前台通过接口传给后台参数,后台根据参数通过接口返回数据给前台。
那么,这些接口要怎么设计才完美高效呢?
场景一
A页面有个登录的需求,我们给A页面造个接口:
doUserLogin: function() {
this.axios.get('user/login')
.then(res => {
if (res.data.status) {
this.user = res.data.data;
}
})
.catch(error => {
console.log(error);
});
},
B页面有个获取用户信息的需求,我们给B页面造个接口:
getUserInfo: function() {
this.axios.get('user/infor')
.then(res => {
if (res.data.status) {
this.user = res.data.data;
}
})
.catch(error => {
console.log(error);
});
},
这样子做,我们在很多页面都造了接口。
可是这样子就存在一个问题:我怎么知道我造了哪些接口,难道一个个页面找吗?
场景二
所有接口的信息我们都在管理中心进行配置
import axios from 'axios';
import store from '../store';
let httpURL = "http://www.xuguobin.club/api/elm/" //这是我服务器的api接口
let localURL = 'http://localhost/api/elm/'; //这是本地koa2的api接口
axios.defaults.baseURL = localURL;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
export default {
//获取用户信息
getUser() {
return axios.get('user/infor');
},
//获取订单
getOrders(orderType) {
return axios.get('user/order?type=' + orderType);
},
//提交订单
submitOrder(order) {
return axios.get('user/submit?order=' + order);
},
//确认收货
confirmOrder(orderId) {
return axios.get('user/confirm?orderId=' + orderId);
},
//提交评价
submitRating(rating) {
return axios.get('user/rating?rating=' + rating);
},
//用户登录
userLogin(user) {
return axios.post('user/login',`username=${user.username}&password=${user.password}`);
},
};
这样子做,所有接口的信息一目了然。增加一个接口,修改一个接口。直接在管理中心处理就好了。而在每个页面中使用这些封装好的接口,例如A页面有个登录的需求:
doUserLogin: function() {
this.api.doUserLogin('user/login')
.then(res => {
if (res.data.status) {
this.user = res.data.data;
}
})
.catch(error => {
console.log(error);
});
},
这样子如果是小型项目的话已经可以了,可是如果是一个大型项目的开发的话,接口的数量是上百个的。如果全都放在管理中心也是比较杂乱的。
并且,判断接口返回的状态码和处理错误信息可以提取成公用代码,没有必要每个接口都写重复代码
场景三
我们设置一个大的管理中心,这个管理中心封装了ajax的一些公共操作
import axios from 'axios'
import setting from './setting'
let httpURL = "http://www.xuguobin.club/api/elm/" //这是我服务器的api接口
let localURL = 'http://localhost/api/elm/'; //这是本地koa2的api接口
axios.defaults.baseURL = httpURL;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
export default class AxiosCache {
constructor() {
this.__config = {}
this.__setting = setting;
this.init();
}
init() {
this.doFlushSetting(CACHE_KEY, )
}
doFlushSetting(key, conf) {
if (!key && typeof key !== 'string') {
return
}
this.__config[key] = conf
}
/*判断状态码*/
resultJudge(code) {
return code
}
/*发送请求数据*/
sendRequest(key, options) {
let send = this.__config[this.settingKey][key];
let self = this;
let baseURL = send.url;
send.method == 'get'
? options.data && (send.url += options.data)
: send.data = options.data
axios(send)
.then(function (response) {
send.url = baseURL;
if (self.resultJudge(response.data.status)) { /*判断状态码*/
options.success(response.data.data)
} else {
options.fail /*如果页面配置了错误处理方法就交给该页面处理,否则统一处理错误信息*/
? options.fail(response.data.data)
: self.handleErrorCase(response.data.status)
}
}).catch(function (error) {
self.handleErrorCase(error)
})
}
/*处理错误信息*/
handleErrorCase(error) {
if (typeof error == 'Number') {
console.log(error)
} else {
alert(error)
}
}
}
同时我们设置很多管理中心继承自这个大的管理中心,
把所有与user相关的接口封装成USerCache:
import BaseCache from '../base/base'
import config from './config'
const CACHE_KEY = 'user_cache_key' //标识符
export default class UserCache extends BaseCache {
constructor () {
super()
this.settingKey = CACHE_KEY
}
init () {
this.doFlushSetting(CACHE_KEY, config)
}
getUser(options) {
this.sendRequest('user-getUser',options)
}
getOrders(options) {
this.sendRequest('user-getOrders',options)
}
getRatings(options) {
this.sendRequest('user-getRatings',options)
}
submitOrder(options) {
this.sendRequest('user-submitOrder',options)
}
confirmOrder(options) {
this.sendRequest('user-confirmOrder',options)
}
submitRating(options) {
this.sendRequest('user-submitRating',options)
}
userLogin(options) {
this.sendRequest('user-userLogin',options)
}
}
另外创建一个文件config配置访问参数:
export default {
'user-getUser': {
url: 'user/infor',
method: 'get'
},
'user-getOrders': {
url: 'user/order?type=',
method: 'get'
},
'user-submitOrder': {
url: 'user/submit?order=',
method: 'get'
},
'user-confirmOrder': {
url: 'user/confirm?orderId=',
method: 'get'
},
'user-submitRating': {
url: 'user/rating?rating=',
method: 'get'
},
'user-userLogin': {
url: 'user/login',
method: 'post'
}
}
而如果A页面有登录的需求的话,只需要这样写就可以了:
getUSer: function() {
this.userCache.getUser({
success: res => this.user = res
})
},