微信小程序封装网络请求

一  . 在utils.js中新建getdata.js


二 . 在getdata.js中写入

//api地址

const apiurl = "(通用端口号)";

//优化,获取数据时显示提示

const pagedata = {

  get(callback, url, data) {

    const token = wx.getStorageSync('token') ? wx.getStorageSync('token') : '';  //判断Token

    wx.showLoading({       

      title: '加载中...',

    })

    wx.request({

      url: apiurl + url,

      data: data,

      method: 'GET',

      header: {

        'content-type': 'application/json', // 默认值

        'Authorization': 'Bearer '+ token        //在Authorization位置放置token

      },

      success: function (res) {

        //隐藏提示

        wx.hideLoading();

        callback('success', res);

      },

      fail: function (err) {


        console.log(err);

      }

    })

  },

  post(callback, url, data) {

    const token = wx.getStorageSync('token') ? wx.getStorageSync('token') : '';

    wx.showLoading({

      title: '加载中...',

    })

    wx.request({

      url: apiurl + url,

      data: data,

      method: 'POST',

      header: {

        'content-type': 'application/json', // 默认值

        'Authorization': 'Bearer '+ token

      },

      success: function (res) {

        //隐藏提示

        wx.hideLoading();

        callback('success', res);

      },

      fail: function (err) {

        console.log(err);

      }

    })

  }

}

//输出

module.exports = {

  apidata: pagedata

}

三 . 写好后 在需要的页面顶部引入文件


四 . 在函数中使用

getdata.apidata.post((state, res) => {

      if (state == 'success') {

        console.log(res)

      }

      }, '/mbssale/api/agent/register',{

        data

      });

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容