// 网络请求文件request.js
class Axios {
constructor(config) {
this.config = Object.assign({
timeout: 300,
dataType: 'json'
}, config);
//拦截器对象
this.interceptor = {
reqQueue: [],
resQueue: [],
request: function(configFunc) {
this.reqQueue.push(configFunc)
},
response: function(successFunc, failFunc) {
this.resQueue.push(successFunc, failFunc)
}
};
//添加GET,POST.PUT.DELETE四种方法
['POST', 'GET', 'PUT', 'DELETE'].reduce((pre, method) => {
pre[method] = function(url, data) {
return this.request.call(this, Object.assign(this.config || {}, {
url,
method: method,
data: data || {}
}))
}
return pre;
}, this);
}
request(conf) {
//执行request拦截器
let config = this.interceptor.reqQueue[0].call(this, conf);
return new Promise((resolve, reject) => {
wx.request({
method: config.method,
url: config.url,
data: config.data || {},
header: config.header || {
'content-type': 'application/json'
},
success(res) {
resolve(res)
},
fail(err) {
reject(err)
}
})
})
//响应拦截器
.then(this.interceptor.resQueue[0] || (res => Promise.resolve(res))) //ok response
.catch(this.interceptor.resQueue[1] || (err => Promise.reject(err))); // fail response
}
};
let axios = new Axios();
//请求拦截器
axios.interceptor.request(function(config) {
console.log('---------请求拦截器-------');
return config || {};
});
//响应拦截器
axios.interceptor.response(res => {
console.log('成功响应拦截')
return Promise.resolve(res);
}, err => {
console.log('失败响应拦截')
return Promise.reject(err)
});
module.exports = axios;
//在另一个界面center.js中测试
const axios = require('../../utils/request.js')
//POST请求
axios.POST('http://134.175.146.136:8080',{name:'lewis'}).then(res =>{
console.log(res)
});
//PUT请求
axios.PUT('http://www.baidu.com',{name:'lewis'}).then(res =>{
console.log(res)
});
//DELETE请求
axios.DELETE('http://www.baidu.com',{name:'lewis'}).then(res =>{
console.log(res)
});
//GET请求
axios.GET('http://www.baidu.com',{name:'lewis'}).then(res =>{
console.log(res)
});
//config配置请参考微信开发文档https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html