小程序模块封装---网络请求

版权声明:本文为楠之枫雪的原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014614038/article/details/81913372

get请求:

function doGet (urlStr){
 return new Promise(function (resolve,reject){
    wx.request({
      url: urlStr,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.statusCode==200){
          resolve(res.data);
        }else{
          resolve('');
        }
      },
      fail: function (err) {
        reject(err);
      }
    })
 });
}

post请求

function doPost(urlStr,postData) {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: urlStr,
      method: 'POST',
      data: postData,
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.statusCode == 200) {
          resolve(res.data);
        } else {
          resolve(res.data);
        }
      },
      fail: function (err) {
        reject(err);
      }
    })
  });
}

请求过程中显示加载圈


 function doGet(urlStr, isHasLoading, loadingTitle) {
   return new Promise(function(resolve, reject) {
     if (isHasLoading) {
       if (!((typeof loadingTitle == 'string')
         && (loadingTitle.constructor == String))) {
         loadingTitle = '';
       }
       wx.showLoading({
         title: loadingTitle,
       })
     }
     wx.request({
       url: urlStr,
       method: 'GET',
       header: {
         'Content-Type': 'application/json'
       },
       success: function(res) {
         wx.hideLoading();
         if (res.statusCode == 200) {
           resolve(res.data);
         } else {
           resolve('');
         }
       },
       fail: function(err) {
         wx.hideLoading();
         reject(err);
       }
     })
   });
 }
 function doGetWithLoading(urlStr, loadingTotle) {
   return doGet(urlStr, true, loadingTotle)
 }

使用:

var netUtil = require('../../utils/NetUtil.js');
  var url = 'http://192.168.4.49:10108/api';
    var params = {  'token':'D2177E95-B3D8-4CAC-90B4-2028A85E987F'}
    netUtil.doPost(url, JSON.stringify(params)).then(function (data) {
     //请求成功回调
      console.log('success:' + JSON.stringify(data));
    },function(error,data){
    //请求失败回调
      console.log('error:' + JSON.stringify(error));
    }).catch(function (reason) {
      console.log('catch exception' + reason);
    });

猜你喜欢

转载自blog.csdn.net/u014614038/article/details/81913372