config.js
const config = {
wssURL: 'wss://www.example.com:8888',
baseURL: 'https://www.example.com'
// baseURL: 'http://example.test'
}
module.exports = config;
request.js
const app = getApp();
const config = require('./config');
class Request {
constructor(parms) {
this.withBaseURL = parms.withBaseURL;
this.baseURL = parms.baseURL;
}
get(url, data) {
return this.request('GET', url, data)
}
post(url, data) {
return this.request('POST', url, data)
}
put(url, data) {
return this.request('PUT', url, data)
}
delete(url, data) {
return this.request('DELETE', url, data)
}
request(method, url, data) {
const vm = this;
data.from = 'mp';
return new Promise((resolve, reject) => {
wx.request({
url: vm.withBaseURL ? vm.baseURL + url : url,
data,
method,
header: {
'token': app.globalData.token,
},
success(res) {
if (res.data.code === -1) {
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const current_url = currentPage.route;
wx.redirectTo({
url: '/pages/bind/index?from=' + current_url//实际路径要写全
})
} else if (res.data.code === 0) {
wx.showToast({
title: res.data.msg,
icon: 'error',
duration: 3000
});
} else {
resolve(res)
}
},
fail() {
reject({
msg: '请求失败',
url: vm.withBaseURL ? vm.baseURL + url : url,
method,
data
})
}
})
})
}
}
const request = new Request({
wssURL: config.wssURL,
baseURL: config.baseURL,
withBaseURL: true
});
module.exports = request;