使用async await封装请求
第一次写文章,大佬们不喜勿喷啊!
封装小程序请求我使用了wepy.js,跟原生有点差别,但是原理都是一样的。
1、使用 async await 封装 axios;
import Axios from 'axios';
const baseUrl = 'http://网络请求路径/';
export default {
async callApi(method, endpoint, data) {
method = method.toUpperCase();
let config = {
method: method,
url: baseUrl + endpoint,
};
method === 'GET' ? config.params = data : config.data = data;
config.headers = {
"Content-Type":"application/x-www-form-urlencoded"
};
let resp = await Axios(config);
return resp.data;
},
async login(username, password) {
let data = await this.callApi('POST', 'admin.base.login', {
username: username,
password: password,
});
return data;
},
}
2、使用 async await 封装 wx.request();
export default {
async apiCalls(opt) {
let {endpoint, method, data} = opt;
let fullurl = 'http://网络请求路径/' + endpoint;
let header = {
'content-type': 'application/json',
};
if (!data) { data = {}; }
let res = await wx.request({
url: fullurl,
method: method,
header: header,
data: data
});
return res.data;
},
async login(username, password) {
let data = await this.apiCalls({
endpoint: 'xxx',
method: 'POST',
data: {
username: username,
password: password
}
});
return data;
},
}
import api from '@/api/data';
async loginIn(username,password){
let data = await api.login(username,password);
console.log(data);
},