微信小程序封装数据请求方法wx.request(Object object)

微信小程序封装数据请求方法wx.request(Object object)

当我们在写微信小程序的时候,避免不了多次使用wx.request(Object object)请求数据
所以!!我们需要封装一下方法方便我们调用
封装之前我们可以先看一下官方文档

https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html
写的比较详细
好的 当我们看完之后我们在 utils文件夹里新建一个http.js文件
在这里插入图片描述
将下面的代码写进http.js中

/**
 * 请求头
 */

var app = getApp()

// var header = {
//   'content-type': 'application/json',
//   'token':  wx.getStorageSync('token')
// }

/**
 * 供外部post请求调用
 */
function post(url, params, onSuccess, onFailed) {
  console.log("请求方式:", "POST")
  request(url, params, "POST", onSuccess, onFailed);

}

/**
 * 供外部get请求调用
 */
function get(url, params, onSuccess, onFailed) {
  console.log("请求方式:", "GET")
  request(url, params, "GET", onSuccess, onFailed);
}

/**
 * function: 封装网络请求
 * @url URL地址
 * @params 请求参数
 * @method 请求方式:GET/POST
 * @onSuccess 成功回调
 * @onFailed  失败回调
 */

function request(url, params, method, onSuccess, onFailed) {

  // var header = {
  //   'content-type': 'application/json',
  //   'token': wx.getStorageSync('token')
  // }
  console.log('请求url:' + url);
  wx.showLoading({
    title: "正在加载中...",
  })
  // console.log("请求头:", header)
  wx.request({
    url: url,
    data: dealParams(params),
    method: method,
    // header: header,
    success: function (res) {
      wx.hideLoading();
      console.log('响应:', res);

      if (res.data) {
        /** start 根据需求 接口的返回状态码进行处理 */
        if (res.statusCode == 200) {
          if (res.data.code == 0) {
            onSuccess(res.data); //request success
          } else if (res.data.code == 401) {
            
          } else {
            onSuccess(res.data); //request success
          }

        } else {
          onFailed(res.data.message); //request failed
        }
        /** end 处理结束*/
      }
    },
    fail: function (error) {
      onFailed(""); //failure for other reasons
    }
  })
}

/**
 * function: 根据需求处理请求参数:添加固定参数配置等
 * @params 请求参数
 */
function dealParams(params) {
  console.log("请求参数:", params)
  return params;
}


// 1.通过module.exports方式提供给外部调用
module.exports = {
  postRequest: post,
  getRequest: get,
}

每个函数封装的都比较清晰

如何使用??

当我们封装好了 将这个js引入到需要的页面(注意引入路径)

var http = require('../../utils/http');

在这里插入图片描述

使用的时候

//这里写路径 因为我把接口域名写在全局 就直接调出来
let url = app.globalData.baseURL
        url = url + '****'
        //需要传的值
        var params = {
          a:1,
          b:2,
          .......
        }
        //直接调用post请求 如果是get请求就是 http.getRequest
        http.postRequest(url, params, function (res) {
          if (判断) {
            //成功
          } else {
          	//失败
            wx.showToast({
              title: res.msg,
              duration: 2000,
              icon: 'none'
            });
          }
        })

这样就可以使用了
然后我们请求时的 请求方式、请求的url、请求参数、响应参数都会打印
在这里插入图片描述
加油搬砖人 此方法时偷我师父的
哈哈哈哈哈哈哈

猜你喜欢

转载自blog.csdn.net/weixin_47284756/article/details/114358045