微信小程序 =》 封装的 wx.request 实现 cookie 保持

xyj2156 小程序 2018-05-12

微信小程序 ☞ wx.request

原理

我们只要从 返回的 header 上获取 cookie 保存到 微信提供的缓存,调用请求的时候从缓存中读取出来加到 请求的 header上就可以实现 cookie 保持。


定义一些用到的 常量 和 函数名

首先定义一个 module 调用的时候在第一行 require 就行了。

  1. cookie 键 内部使用这个常量,方便修改。
  2. debug 输出函数 通过判断这个值,是否执行输出。
  3. 日志输出函数 http_log
  4. 执行函数 request
  5. 快捷 POST 方式
  6. 快捷 GET 方式
  7. 保存 cookie 函数
  8. 公共执行回调函数 exec
  9. 定义一个重写 参数的函数,这样直接拿这个参数 传入 wx.request 就行了。

分析下我们需要的功能:

  1. 修改 headerheader 中默认的 Content-Typeapplication/json 不符合常用的 POST GET 获取 为了方便,修改成 application/x-www-form-urlencoded
  2. 参数定义和原来的一样,
  3. post 和 get 的快捷调用
  4. 请求网络之前 获取存储的 cookie (这里我用的异步),
  5. 公共执行函数 检测回调 并执行。
  6. 模块的导出

首先 定义常量和日志输出方法

这样方便后续调试和使用。

const debug = wx.debug === true;  // 定义调试模式
const cookie = 'Jief_cookie'; // 定义 存储 cookie 的键

// 日志输出,添加前缀 方便过滤
function http_log() {
    if(!debug) return false;
    Array.prototype.unshift.call(arguments, 'http.js 组件 ');
    console.info.apply(this, arguments);
}

写辅助函数 公共方法中用的到

// 执行回调函数,第一个参数传入方法,参数依次传入即可
function exec(fn) {
    var arg = Array.prototype.slice.call(arguments, 1);
    fn && typeof fn === 'function' && (fn.apply(null, arg), http_log('执行回调',fn.name));
}

// 根据传入的参数生成 直接请求wx.request 的参数
function rewriteData(data){
    // 判断 header 是不是设置了
    data.header = typeof data.header === 'object' ? data.header : {};
    // 判断header 有没有设置 Content- Type 如果设置了 不会覆盖
    data.header['Content- Type'] || (data.header['Content-Type'] = 'application/x-www-form-urlencoded');
    // 重写 data 的方法
    let success = data.success;
    let fail = data.fail;
    let complete = data.complete;
    data.success = (res) => {
        if (isSuccess(res.data)) {
            http_log(data.url, '请求成功', res);
            exec(success, res, res.data);
        } else {
            http_log(data.url, ' ', res);
            exec(fail, res, res.data);
        }
    };
    data.fail = (res) => {
        http_log(data.url, '请求失败', res);
        exec(fail, res, res.data || false);
    };
    data.complete = (res) => {
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        res && res.header && res.header['Set-Cookie'] && setCookie(res.header['Set-Cookie']);
        http_log(data.url, '请求完成', res);
        exec(complete, res, res.data || false);
    };
    return data;
}

// 设置 cookie 的方法
function setCookie(cookie_value) {
    wx.setStorage({
        key: cookie,
        data: cookie_value,
        complete: (res) => {
            http_log('设置 cookie 完成', res, this);
        }
    });
    return true;
}

写公共方法

function request(data) {
    http_log('开始获取cookie 并准备请求网络');
    if(typeof data !== 'object' || typeof (data.url) !== 'string'){
        console.warn('http.js', 'data 不是对象 或者 data.url不是字符串', data);
        return false;
    }
    wx.showLoading({
        title: '加载中…',
    });
    wx.showNavigationBarLoading();
    // 重新设置data 的值
    http_log('重新设置 data');
    data = rewriteData(data);
    // 开始获取 存储的 cookie
    wx.getStorage({
        key: cookie,
        // 这里使用完成,判断有没有cookie 来决定是不是需要设置。
        complete: function (res) {
            // 有数据 设置 cookie
            if (res.data) {
                data.header['Cookie'] = res.data;
            }
            http_log('获取cookie 完成', res, 'header 是', data.header);
            wx.request(data);
        },
    });
    return true;
}

写快捷方法

function post(data) {
    if(!data || typeof data !== 'object'){
        http_log('传进来的参数是', data);
        throw new Error('传进来的参数不是对象');
    }
    data.method = "POST";
    request(data);
}

function get(data) {
    if (!data || typeof data !== 'object') {
        http_log('传进来的参数是', data);
        throw new Error('传进来的参数不是对象');
    }
    data.method = 'GET';
    request(data);
}

导出 方法

module.exports = {
    request: request,
    get: get,
    post: post
};

结束

这样我们直接require 这个模块就可以用了。

PREV
samba 服务器的配置
NEXT
git 与 tortoiseGit 结合时 遇到的坑

评论(0)

评论已关闭