问题描述
项目中接口使用restful api风格,需要携带token,当http状态码为401时需要重新发起登录,为方便统一管理将小程序网络请求原生接口封装
代码
utils/request.js 请求类
token存在globalData中,默认携带,服务端判断错误时可以登录更新
/**** 网络请求相关操作* statusCode为401时跳转到重新登录更新token*/
//接口地址var _api = 'http://www.aaa.com/';
function
curl(url, data, success, fail, method)
{
var token = getApp().globalData.token;
wx.request({
url: _api + url,
header: {
'Content-Type': 'application/json',
'Authorization': token
},
method: method,
data: data,
success: function (res) {
if (res.statusCode == 401) {
toLogin();
}
success(res);
},
fail: function (error) {
fail(error);
}
});
}
/*** get方式获取数据*/
function _get(url, data, success, fail) {
curl(url, data, success, fail, 'GET');
}
function post(url, data, success, fail) {
curl(url, data, success, fail, 'POST');
}
function put(url, data, success, fail) {
curl(url, data, success, fail, 'PUT');
}
function _delete(url, data, success, fail) {
curl(url, data, success, fail, 'DELETE');
}
function toLogin() {
wx.navigateTo({
url: '/pages/login/login'
})
}
module.exports = {
GET: _get,
POST: post,
PUT: put,
DELETE: _delete,
URL: _api,
}
使用
request.GET(接口地址, '参数',成功回调函数,失败回调函数)
先引入请求类
var request = require("../../utils/request.js");
/**
* 获取幻灯片
*/
getSlideList() {
var that = this;
var slide = cache.cache('slide');
if (slide) {
that.setData({
slideList: slide,
})
} else {
request.GET('slide', '',
function (res) {
if (res.data.code == 0) {
that.setData({
slideList: res.data.data.data,
})
cache.cache('slide',res.data.data.data);
}
},function (error) {
console.log(error);
})
}
},