封装小程序网络请求

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
        })
        }
      })
}
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,190评论 4 61
  • 世世如艰,无往辛苦一朝。 不往如前,不外乎荒唐一世。 心如前往,落日华丽谢幕。 提琴一把,落下糟糟酒酿。 铮铮傲骨...
    化作枫阅读 1,690评论 0 1
  • 日行 晨起,看书 练习陌拜话术 知乎上寻找如何陌拜 整理自己的打电话话术,并用于实践(打60通) 跟踪客户(没有及...
    蔺旭玮阅读 1,027评论 0 0
  • “处暑先生!处暑先生!你给我站住!”我气鼓鼓地追着前面那个扛着大西瓜提着蚂蚱笼子的黄绿色的人。 处暑先生不小心撞上...
    dimplee阅读 3,038评论 3 1