request请求


本文参考守望轩小程序里的封装方法

守望轩 也是一个 开源的小程序 用wordpress 啥写的具体我也不清楚不过写的很好有意向可以去看看了解下,话不多说开始说内容。

“request” 发起网络请求,官网比我说的更清楚 啊哈哈 注:官方文档

image.png


给大家推荐一个好用的东西(调试接口)https://jsonplaceholder.typicode.com/ 里面有接口 及回调数据 基本够 练手 了


wx.request({
      url: 'https://jsonplaceholder.typicode.com/users',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'GET', //请求方式
      success: function(res) { // 成功回调
        console.log(res)
      },
      fail: function(res) {},//请求失败回调
      complete: function(res) {},// 成功 或失败都会回调
    })
//请求成功后你会在控制台看到十条 用户信息 。
接口调用成功


请求(request)封装无外乎 将 url、data、success、fail一些 封装起来 。

/* 新建一个js文件   将下方代码复制进去 */
function wxPromisify(fn) {
    return function (obj = {}) {
        return new Promise((resolve, reject) => {
            obj.success = function (res) {
                //成功
                resolve(res)
            }
            obj.fail = function (res) {
                //失败
                reject(res)
            }
            fn(obj)
        })
    }
}
//无论promise对象最后状态如何都会执行
Promise.prototype.finally = function (callback) {
    let P = this.constructor;
    return this.then(
        value => P.resolve(callback()).then(() => value),
        reason => P.resolve(callback()).then(() => { throw reason })
    );
};
/**
 * 微信请求get方法
 * url
 * data 以对象的格式传入
 */
function getRequest(url, data) {
    var getRequest = wxPromisify(wx.request)
    return getRequest({
        url: url,
        method: 'GET',
        data: data,
        header: {
            'Content-Type': 'application/json'
        }
    })
}

/**
 * 微信请求post方法封装
 * url
 * data 以对象的格式传入
 */
function postRequest(url, data) {
    var postRequest = wxPromisify(wx.request)
    return postRequest({
        url: url,
        method: 'POST',
        data: data,
        header: {
            "content-type": "application/json"
        },
    })
}

module.exports = {
    postRequest: postRequest,
    getRequest: getRequest
}

复制完 注意下目录 我是将其放在utils目录下。在index.js 引用的

/*引用 创建的js文件*/
import Request from "../../utils/wxRequest.js";
var data = { // 不用data 参数
      
    };
    var url = app.globalData.https+'users'; //url
    var getLikeRequest = Request.getRequest(url, data);
    getLikeRequest.then(response => {
      console.log(response)// 成功回调数据  将你需要的数据setdata渲染到页面就好
    }).catch(res=>{
      //失败回调
    })
//跟上文对比 是不是比request 简洁了些 。

守望轩的小程序开源地址 https://github.com/iamxjb/winxin-app-watch-life.net

今天就到这喜欢的点个喜欢蟹蟹。

你可能感兴趣的:(request请求)