// 網(wǎng)絡(luò)請求文件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) {
? ? //執(zhí)行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)
? ? ? ? ? }
? ? ? ? })
? ? ? })
? ? ? //響應(yīng)攔截器
? ? ? .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 || {};
});
//響應(yīng)攔截器
axios.interceptor.response(res => {
? console.log('成功響應(yīng)攔截')
? return Promise.resolve(res);
}, err => {
? console.log('失敗響應(yīng)攔截')
? return Promise.reject(err)
});
module.exports = axios;
//在另一個(gè)界面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配置請參考微信開發(fā)文檔https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html