小程序

微信小程序之交互(七)

2019-12-11  本文已影响0人  笑红尘123

一、网络请求小程序提供了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
}
上一篇 下一篇

猜你喜欢

热点阅读