微信请求封装

1.在utils文件夹建一个public.js
const baseUrl = '###';//公共路径

const http = ({ url = '', param = {}, ...other } = {}) => {
    wx.showLoading({
        title: '请求中,请耐心等待..'
    });
    let timeStart = Date.now();
    return new Promise((resolve, reject) => {
        wx.request({
            url: baseUrl + url,
            data: param,
            header: {
                'content-type': 'application/json' // 默认值 ,另一种是 "content-type": "application/x-www-form-urlencoded"
            },
            ...other,
            complete: (res) => {
                wx.hideLoading();
                console.log(`耗时${Date.now() - timeStart}毫秒`);
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data)
                } else {
                    reject(res)
                }
            }
        })
    })
}

// const getUrl = (url) => {
//     if (url.indexOf('://') == -1) {
//         url = baseUrl + url;
//     }
//     return url
// }

// get方法(获取数据)
const get = (url, param = {}) => {
    return http({
        url,
        param
    })
}

//post方法 (存储或者获取数据)
const post = (url, param = {}) => {
    return http({
        url,
        param,
        method: 'post'
    })
}

//put方法(更新数据)
const put = (url, param = {}) => {
    return http({
        url,
        param,
        method: 'put'
    })
}

//delete方法 (删除数据)
const _delete = (url, param = {}) => {
    return http({
        url,
        param,
        method: 'delete'
    })
}
module.exports = {
    baseUrl,
    get,
    post,
    put,
    _delete
}
2.发送请求
const api = require('../../utils/public.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ID:"0",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 单个get请求1
    api.post("pnt/getCategories").then(res => {
      console.log(res,"成功请求")
    }).catch(e => {
      console.log(e,"失败请求")
    }) 
    
    // 单个get请求2
    api.get(`sitemsg/getSiteMsgByConId?conId=${this.data.ID}`).then(res => {
      console.log(res,"成功请求")
    }).catch(e => {
      console.log(e,"失败请求")
    })
    
    //单个post请求
    api.post("sitemsg/getSiteMsgByConId",{conId:this.data.ID}).then(res => {
      console.log(res,"成功请求")
    }).catch(e => {
      console.log(e,"失败请求")
    })

	// 一个页面多个请求
   Promise.all([
      api.get("pnt/getCategories"),
       api.post("sitemsg/getSiteMsgByConId",{conId:this.data.ID})
  ]).then(result => {
      console.log(result)
  }).catch(e => {
      console.log(e)
    })
  },
})

https://www.it610.com/article/1279397810260688896.htm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值