小程序 requestUtil 工具类

本贴最后更新于 1941 天前,其中的信息可能已经沧海桑田

#小程序工具类 requestUtils

1.前言

开发小程序已经有一段时间了,都没有写过小程序相关的文章,踩过坑挺多,把这些坑记下来,下次就不会再犯了。
小程序自带的请求方法不是特别方便,无意中得到了一个工具类,因此把这个工具类分享出来

2.工具类详情

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//添加请求根目录
var rootDocment = 'https://yjt.*****.com/wechat';
function req(url, data, cb) {
  wx.request({
    url: rootDocment + url,
    data: data,
    method: 'post',
    header: { 'Content-Type': 'application/x-www-form-urlencoded' },
    success: function (res) {
      return typeof cb == "function" && cb(res.data)
    },
    fail: function () {
      return typeof cb == "function" && cb(false)
    }
  })
}

function getReq(url, data, cb) {
  wx.request({
    url: rootDocment + url,
    data: data,
    method: 'get',
    header: { 'Content-Type': 'application/x-www-form-urlencoded' },
    success: function (res) {
      return typeof cb == "function" && cb(res.data)
    },
    fail: function () {
      return typeof cb == "function" && cb(false)
    }
  })
}

// 去前后空格  
function trim(str) {
  return str.replace(/(^\s*)|(\s*$)/g, "");
}

// 提示错误信息  
function isError(msg, that) {
  that.setData({
    showTopTips: true,
    errorMsg: msg
  })
}

// 清空错误信息  
function clearError(that) {
  that.setData({
    showTopTips: false,
    errorMsg: ""
  })
}

function formatTime(time) {
  var year = time.getFullYear();
  var month = time.getMonth() + 1;
  var date = time.getDate();
  var hour = time.getHours();
  var minute = time.getMinutes();
  var second = time.getSeconds();
  return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}

module.exports = {
  formatTime: formatTime,
  req: req,
  trim: trim,
  isError: isError,
  clearError: clearError,
  getReq: getReq,
  formatTime: formatTime
}  

3.用法

page 页面顶部定义

var wechatUtil = require('../../utils/wechatRequest.js');

发起请求

wechatUtil.req("/member/update",{
      "unionId": unionId,
      "username": username,
      "headImg": headImg
    },function(res){
	    //res为返回的数据
      if(res.resultCode == 200){
        console.log("更新用户信息成功");
        console.log(res);
        // that.setData({
        //   member:res.resultContent
        // });
      }else{
        console.log("更新用户信息失败");
        console.log(res);
      }
    })

4.结尾

好了,一个简单的工具类结束了,拜拜

  • B3log

    B3log 是一个开源组织,名字来源于“Bulletin Board Blog”缩写,目标是将独立博客与论坛结合,形成一种新的网络社区体验,详细请看 B3log 构思。目前 B3log 已经开源了多款产品:SymSoloVditor思源笔记

    1083 引用 • 3461 回帖 • 287 关注
  • 小程序
    76 引用 • 218 回帖 • 2 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...