1、这里使用了gitHub上面封装好的底层请求链接在此https://github.com/tildeio/rsvp.js。项目中创建NetUtil.js文件来再次封装请求
/**
* 基于Promise封装网络请求
* 引入了https://github.com/tildeio/rsvp.js
*/
// var Promise = require('../libs/bluebird/browser/bluebird.min');
import { Promise } from '../libs/rsvp-latest.min';
export default class NetUtil {
// post 请求
static postJson(url, data) {
return NetUtil.requestJson(url, data, "post");
}
// get 请求
static getJson(url, data) {
return NetUtil.requestJson(url, data, "get");
}
static requestJson(url, data, method) {
return new Promise(function (resolve, reject) {
wx.request({
"method": method,
"url": url,
"data": data,
"header": {
'Content-Type': 'application/json',
'Cookie': 'userid='+wx.getStorageSync(getApp().Config.UsercookieKey)
},
success: function (res) {
resolve(res);
},
fail: function (err) {
reject(err);
}
})
});
}
}
在项目中这样使用,这里再次封装一层创建API.js用于封装所有项目中使用到的请求
import NetUtil from "/utils/netUtil.js"
const HOST = getApp().Config.Host
const ActionClient = 'action/client'
export default class API {
// 获取子帐号列表
static get_Child_UserList(user_id){
return NetUtil.getJson(
`${HOST}/${ActionClient}/getChildUserList`,
{
user_id: user_id
}
)
}
}
在需要用到的位置,进行调用
import api from '/api/api.js'
Page({
data:{
},
onLoad:function(e){
api.get_Child_UserList('').then((res) => {
let code = res.data.code
console.log(res.data)
if (code == 0) {
}
this.setData({
user_list: childs
})
}
})
}
})
网友评论