微信小程序之交互(七)

一、网络请求小程序提供了wx.request

// 官方例子
wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {
     x: '' ,
     y: ''
  },
  header: {
      'content-type': 'application/json' // 默认值
  },
  success: function(res) {
    console.log(res.data)
  }
})

小程序支持ES6,那么就应该支持Promise 了,很开心~, 话不多说直接上代码吧

二、网络请求封装

const baseUrl = 'https://localhost:3000';

const http = ({ url = '', param = {}, ...other } = {}) => {
    wx.showLoading({
        title: '请求中,请耐心等待..'
    });
    let timeStart = Date.now();
    return new Promise((resolve, reject) => {
        wx.request({
            url: getUrl(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
    })
}

const _post = (url, param = {}) => {
    return http({
        url,
        param,
        method: 'post'
    })
}

const _put = (url, param = {}) => {
    return http({
        url,
        param,
        method: 'put'
    })
}

const _delete = (url, param = {}) => {
    return http({
        url,
        param,
        method: 'put'
    })
}
module.exports = {
    baseUrl,
    _get,
    _post,
    _put,
    _delete
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 写在前面 微信小程序出来也蛮久了,经过了市场的考验,已经站稳脚跟,融入到了各行各业,市场需求激增打来的是开发人员的...
    月梦佳期阅读 1,791评论 1 1
  • 本文发表至今已有一段时间,错别字多、文笔混乱、内容过于陈旧。本人建议读者不必细究,大概浏览即可,最新的开发指南还是...
    Oopsguy阅读 6,355评论 2 19
  • 也许今生遇到你是上辈子求了五百遍才得到的眷恋 我曾是你脚边修炼的莲花,你偶尔浇灌我的花蕊,我愿意把心给你。 你感冒...
    再简单不过了阅读 130评论 0 3
  • 我的表弟在6月19日出生了!我期待着他的到来,最为好奇的就是他的那张脸。 妈妈抱着表弟,他被一个棉被裹起来...
    少女故事阅读 291评论 0 0
  • 故事是这样的 牛耕田回来,躺在栏里,疲惫不堪地喘着粗气,狗跑过来看它。 “唉,老朋友,我实在太累了。”牛诉着苦,“...
    山中捡石阅读 63评论 0 1

友情链接更多精彩内容