微信小程序封装wx.request接口调用

1、判断登录是否过期(主要判断token、有效时间、是否登录的状态)

2、过期操作的流程获取cache_key缓存

    执行成功的回调

    (1)在用户授权成功的情况下调用wx.getUserInfo

    (2)将用户信息作为参数调用后端的登录接口,执行登录成功的回调重新保存token、userinfo、expiresTime(有效时间)、缓存wx.setStorage({ key: 'cache_key', data: res.data.cache_key })

 

config.js

module.exports = {
  // 请求域名 格式: https://您的域名
  HTTP_REQUEST_URL:'https://******.cn',

  // 请求头
  HEADER:{
    'content-type': 'application/json'
  },
  // 回话密钥名称 
  TOKENNAME: 'Authori-zation',
}

request.js

import util from './util.js';
import authLogin from './autuLogin.js';
import { HEADER , TOKENNAME} from './../config.js';
/**
 * 发送请求
 */
export default function request(api, method, data, {noAuth = false, noVerify = false})
{
  let Url = getApp().globalData.url, header = HEADER;
  if (!noAuth) {
    //登录过期自动登录
    if (!util.checkLogin()) return authLogin().then(res => { return request(api, method, data, { noAuth, noVerify}); });
  }
  
  if (getApp().globalData.token) header[TOKENNAME] = 'Bearer ' + getApp().globalData.token;

  return new Promise((reslove, reject) => {
    wx.request({
      url: Url + '/api/' + api,
      method: method || 'GET',
      header: header,
      data: data || {},
      success: (res) => {
        if (noVerify)
          reslove(res.data, res);
        else
          reject(res.data.msg || '系统错误');
      },
      fail: (msg) => {
        reject('请求失败');
      }
    })
  });
}

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = (api, data, opt) => request(api, method, data, opt || {})
});

演示

test.js编写接口:

import request from "./../utils/request.js";

export function test(obj){
  return request.get("test",obj);
}

调用接口


import { test } from '../../../api/test.js';

Page({

  data: {},
  onLoad: function (options) {
    this.test();
  },

  test: function(){
    test({}).then(res => {
      console.log(res);
    });
  }
})

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值