小程序请求Promise的简单封装

uni app 开发小程序请求封装

function request(url, data = {}, method = "POST", header = "application/x-www-form-urlencoded",showLoding=true) {
  let token=uni.getStorageSync('USR-TOKEN');
  console.log("--",token);
 if(showLoding){
   uni.showLoading({
    	title: '加载中'
   });	 
 };
  return new Promise(function (resolve, reject) {
      uni.request({
          url: url,
          data: data,
          method: method,
          header: {
              'Content-Type': header,
               'USR-TOKEN': token
          },
          success: function (res) {
			  uni.hideLoading();
			  if(res.statusCode==200||res.statusCode==204){
				  resolve(res);
			  }else{
				 uni.showModal({
				   title: '提示',
				   content: res.data,
				   showCancel:false,
				 }) 
			  }
          },
          fail: function (err) {
              uni.hideLoading();
              uni.showModal({
                title: '提示',
                content:err,
                showCancel:false,
              })
              reject(err)
          }
      })
  });
}
export{
	request
}

原生小程序请求封装基本上没啥区别

/**
 * 封微信的的request
 */
function request(url, data = {}, method = "POST", header = "application/x-www-form-urlencoded") {
    wx.showLoading({
        title: '加载中...',
    });
    return new Promise(function (resolve, reject) {
        wx.request({
            url: url,
            data: data,
            method: method,
            header: {
                'Content-Type': header,
                'Access-Token': wx.getStorageSync('token')
            },
            success: function (res) {
                wx.hideLoading();
                if(res.statusCode==200||res.statusCode==204){
				   resolve(res);
			     }else{
				 wx.showModal({
				   title: '提示',
				   content: res.data,
				   showCancel:false,
				 }) 
			  }
            },
            fail: function (err) {
                wx.hideLoading();
                reject(err)
            }
        })
    });
}

module.exports = {
    request
}

在用到的地方

let util = require('../../utils/util.js');
let api = require('../../config/api.js');
//调用
  util.request(api.CartUpdate, {},method,header).then(function (res) {
        that.setData({
        
        });

api.js这个文件用来放接口

const API_BASE_URL = 'http://localhost:8080';
module.exports = {
    SHOPCART: API_BASE_URL + '/item/cart', //新品首发
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值