微信小程序带cookie的request请求代码封装(小程序使用session)

时间:2024-03-08 10:40:18

微信小程序带cookie的request请求可,以使服务端知道是同一个客户端请求. session_id会不变,从而很好的使用服务端的session.

写一个工具函数,直接导入使用即可,接口同 wx.request 。会自动设置和更新 cookie。

const request = function (obj) {
    //设置cookie缓存
    if(obj.fail){
        obj.fail = function(err){
            wx.setStorageSync(\'cookie\', err.header[\'Set-Cookie\']);
            obj.fail(err);
        };
    }
    else{
        obj.fail = function (err) {
            wx.setStorageSync(\'cookie\', err.header[\'Set-Cookie\']);
        };
    }
    if(obj.success){
        obj.success = function (res) {
            wx.setStorageSync(\'cookie\', res.header[\'Set-Cookie\']);
            obj.success(res);
        };
    }
    else{
        obj.success = function (res) {
            wx.setStorageSync(\'cookie\', res.header[\'Set-Cookie\']);
        };
    }

    //设置请求头
    if(obj.header){
        obj.header = {
            \'Cookie\': wx.getStorageSync(\'cookie\'),
            "Content-Type": "application/x-www-form-urlencoded",
            ...obj.header
        };
    }
    else{
        obj.header = {
            \'Cookie\': wx.getStorageSync(\'cookie\'),
            "Content-Type": "application/x-www-form-urlencoded",
        };
    }

    wx.request(obj);
};

module.exports = {
    request: request
};

 

下面是我自己封装的 util.js :

const Promise = require(\'./es6-promise.js\');

//封装Request请求方法
function requst(url, method, data = {}) {
  const app = getApp();
  if (app.globalData.token)
  {
    //console.log("token有值:" + app.globalData.token);
    data.token = app.globalData.token;
  }

  wx.showNavigationBarLoading()
  data.method = method
  return new Promise((resove, reject) => {
    wx.request({
      url: url,
      data: data,
      header: {
        \'Cookie\': wx.getStorageSync(\'cookie\'),
        "Content-Type": "application/x-www-form-urlencoded",
      },
      method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      success: function (res) {
        wx.hideNavigationBarLoading()
        wx.setStorageSync(\'cookie\', res.header[\'Set-Cookie\']);
        resove(res.data)
      },
      fail: function (msg) {
        console.log(\'reqest error\', msg)
        wx.hideNavigationBarLoading()
        wx.setStorageSync(\'cookie\', res.header[\'Set-Cookie\']);
        reject(\'fail\')
      }
    })
  })
}


module.exports = {
  requst: requst,

}

 

使用:

var util = require("../../../utils/util");//工具类


/**
   * 获得收藏商家列表
   */
  getFavoriteShop: function (e) {
    wx.showToast({ title: \'加载中...\', icon: \'loading\' });//显示加载框
    let that = this;
    let url = host + "api/prints/user/favoriteshoplist";
    let method = method;
    let data = {
      "user_id": user_id,
      "page": this.data.page,
      "size": this.data.size,
    }
    let result = util.requst(url, method, data);
    result.then(function (res) {
      wx.hideToast();//隐藏加载框
      console.log(res);
      if (res.code == 0) {
        let shop_list = res.data;
        //数组合并
        that.data.shop_list = that.data.shop_list.concat(shop_list);
        that.data.page++;
        that.setData({ shop_list: that.data.shop_list, page: that.data.page });
      }
      else {
        wx.showToast({ title: res.msg, icon: \'none\', duration: 1000, mask: true });
        return false;
      }

    }).catch(function (res) {
      wx.hideToast();//隐藏加载框
      //console.log(res);
    });
  },

 

 

转: https://www.jianshu.com/p/b4740ac347cd