代码
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);
})
}
}