微信小程序> 微信小程序请求封装带token认证

微信小程序请求封装带token认证

浏览量:480 时间: 来源:虹枫

 request.js

var apiHost = "http://localhost:5003/";var tokenKey = "token";// 登录地址, 根据这个地址来设置tokenvar logInUrl = "/Account/LogInForMiniProgram";// 例外不用token的地址var exceptionAddrArr = [  'http://localhost:8080',];/**  * @param url:String  require(必需) 请求地址相对路径 * @param data:Object   可选  请求数据 * @param success:Function  可选   成功回调函数 * @param fail:Function     可选    失败回调函数 */function getRequest(url, data, success, fail) {  CreateHeader(url, function (header) {    wx.request({      url: apiHost + url,      method: 'GET',      data: data,      header: header,      success: function (res) {        if (success && typeof success === "function") {          success(res);        }      },      fail: function (error) {        if (fail && typeof fail === "function") {          fail(error);        } else {          console.log(error);        }      }    })  });}/**  * @param url:String  require(必需) 请求地址相对路径 * @param data:Object   可选  请求数据 * @param success:Function  可选   成功回调函数 * @param fail:Function     可选    失败回调函数 */function postRequest(url, data, success, fail) {  CreateHeader(url, function (header) {    wx.request({      url: apiHost + url,      method: 'POST',      data: data,      header: header,      success: function (res) {        if (url === logInUrl) {          wx.setStorage({            key: tokenKey,            data: res.data.result          })        }        if (success && typeof success === "function") {          success(res);        }      },      fail: function (error) {        if (fail && typeof fail === "function") {          fail(error);        } else {          console.log(error);        }      }    })  });}/**  * @param url:String    请求地址(根据请求地址判断是否添加token) * @param complete:Function 回调函数 */function CreateHeader(url, complete) {  var header = {    'content-type': 'application/json'  }  if (exceptionAddrArr.indexOf(url) == -1) {  //排除请求的地址不需要token的地址    wx.getStorage({      key: tokenKey,      success: function (res) {        header.Authorization = 'Bearer ' + res.data;      },      fail: function (error) {        console.log(error);      },      complete: function () {        complete && typeof complete === 'Function' ? complete(header) : null;      }    });  } else {    complete && typeof complete === 'Function' ? complete(header) : null;  }}module.exports.getRequest = getRequest;module.exports.postRequest = postRequest;

用户可根据自己的项目适当修改.

版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

热门模板

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎