微信小程序 wx.request请求封装

微信小程序 wx.request请求封装

摘要:为了项目的可维护性更高,我们通常会对wx.request请求进行封装。本片文章 重点讲解如何封装wx.request请求

一.文件列表下创建文件 http.js
在这里插入图片描述
二.在此文件下封装函数

/****
 * wx.request 封装
 */
const apiHttp = "https://***.****.com/***/***/***.";
const socketHttp = "https://***.****.com/***/***/***.";
function fun(url, method, data, header) {
  data = data || {};
  header = header || { 'content-type': 'application/json'};
  let user_id = wx.getStorageSync("user_id");
  if (user_id) {
    data.user_id = user_id;
  }
  //wx.showNavigationBarLoading();
  wx.showLoading();
  let promise = new Promise(function (resolve, reject) {
    wx.request({
      url: apiHttp + url,
      header: header,
      data: data,
      method: method,
      success: function (res) {
        if (typeof res.data === "object") {
          if (res.data.code) {
            if (res.data.code === 410) {
              /*wx.showToast({
                title: "为确保能向您提供最准确的服务,请退出应用重新授权",
                icon: "none"
              });*/
              console.log('请重新登录')
              reject("请重新登录");
              wx.redirectTo({
                url: '../index/index',
              })
            } 
          }
        }
        resolve(res);
      },
     // fail: reject,
     fail:function(){
        wx.redirectTo({
          url: '../404/404',
        })
     },
      complete: function () {
        //wx.hideNavigationBarLoading();
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  });
  return promise;
}
module.exports = {
  apiHttp: apiHttp,
  socketHttp: socketHttp,
  "get": function (url, data, header) {
    return fun(url, "GET", data, header);
  },
  "post": function (url, data, header) {
    return fun(url, "POST", data, header);
  }
};

三.页面中引用封装好的函数

var $http = require('../../utils/http.js'); //引入封装函数路径


  request_index_info: function() { //使用封装好的函数
    var $this = this;
    $http.post('index/index',{
		//传入参数,没有可不填
	}).then(res => {
        //成功回调
      }).catch(err => {
        //异常回调
        console.log('请求失败', err);
      });
  },

前端进阶精选:点此去

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值