手把手教媳婦寫代碼-微信小程序網(wǎng)絡(luò)請求封裝簡易版的axios

// 網(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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容