美文网首页
小程序请求接口的封装

小程序请求接口的封装

作者: 想你一些 | 来源:发表于2019-10-09 15:48 被阅读0次

封装的js文件

/**

*  POST 请求

*/

function POST(url, params, success, fail) {

  params.token = token;

  params.appid = api.APPID;

  console.log('请求路径:' + url);

  console.log('POST请求参数:', params);

  wx.request({

    method: "POST",

    url: `${url}`,

    data: params,

    header: {

      'Content-Type': 'application/x-www-form-urlencoded',

      // 'Content-Type': 'application/json',两种方式

      'Cookie': 'token=' + token,

      'token': token,

    },

    success: function(res) {

      console.log('版本:' + Edition);

      console.log('请求路径:' + url);

      console.log('POST请求参数:', params);

      console.log("结果:", res);

      if (res.data.code == 200) {

        var data = res.data.data;

        // if (data) {

        // 请求成功

        // 返回纯数据

        success(data);

        // }

    } else {

      if(res.data.code == 409) {

    // 跟后端约定数据为空的时候返回409 数据为空,页面上就会收到空数组

    success([]);

    return;

  }

  if (res.data.code == 402 || res.data.code == 405) {

// 跟后端约定用户没有登录就返回402、405 数据为空,就会调用封装好的登录接口重新登录  

 // 403未登录  401 token过期

    console.log('登录过期了')

    login(function (res) {

      console.log('调用登录', res)

//登录完重新调用接口

      POST(url, params, success, fail);

    }, function (err) {

    })

  } else {

    wx.showModal({

      title: '系统提示',

      content: res.data.msg,

      showCancel: false,

    })

    // 按失败返回

    fail(res);

  }

}

    },

    fail: function(err) {

      console.log('请求路径:' + url);

      console.log('POST请求参数:', params);

      console.log("请求失败,失败原因:", err);

      fail(err);

    }

  })

}

//其他接口封装也可以写在这里,一起暴露出去

const conif = {

  POST: POST, //  POST网络请求

}

module.exports = conif  //把接口暴露出来,页面上可以调用

页面的调用

页面上引进改js文件

var http = require('../封装的.js');

http.POST(url,data //传入的参数 ,function(res){  //成功的回调函数

},function(err){  //失败的回调函数

})

相关文章

网友评论

      本文标题:小程序请求接口的封装

      本文链接:https://www.haomeiwen.com/subject/zpjgpctx.html