日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

小程序仿 axios 请求封装

發布時間:2025/3/21 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 小程序仿 axios 请求封装 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、新建request.js

/** 功能:小程序仿 axios 的請求封裝*/ export default class Request {// 配置項configure = {baseURL: '', // 請求url地址header: {'content-type': 'application/json;charset=utf-8'}, // headermethod: 'GET', // 請求的類型,支持get,post,put,delete等dataType: 'json', // 返回的數據格式,默認jsonresponseType: 'text', // 響應的數據格式,默認textdata: {}, // 傳參timeout: 3 * 1000, // 請求超時時間}// 攔截器interceptors = {request: {use: (configCb) => {if (configCb) this.interceptors.request.before = configCb;},before: (configCb => {return configCb;})},response: {use: (successCb, errorCb) => {if (successCb) this.interceptors.response.success = successCb;if (errorCb) this.interceptors.response.error = errorCb;},success: (successCb => successCb),error: (errorCb => errorCb),}}// 構造器constructor(props) {this.configure = Object.assign(this.configure, props);}// 提供create方法注入參數static create(configure = {}) {return new this(configure);}// 支持以下 http 請求方式,如果修改請求類型,設置 header 的 content-type 覆蓋默認的即可get(url, data = {}, header = { 'content-type': 'application/json;charset=utf-8' }) {return this.request('GET', url, data, header);}post(url, data = {}, header = { 'content-type': 'application/x-www-form-urlencoded;charset=utf-8' }) {return this.request('POST', url, data, header);}put(url, data = {}, header = {}) {return this.request('PUT', url, data, header);}delete(url, data = {}, header = {}) {return this.request('DELETE', url, data, header);}head(url, data = {}, header = {}) {return this.request('HEAD', url, data, header);}options(url, data = {}, header = {}) {return this.request('OPTIONS', url, data, header);}trace(url, data = {}, header = {}) {return this.request('TRACE', url, data, header);}connect(url, data = {}, header = {}) {return this.request('CONNECT', url, data, header);}// 判斷是否傳的url中帶有http前綴,有則不會拼加baseUrlisProtocol(url) {return /(http|https):\/\/([\w.]+\/?)\S*/.test(url);}// request封裝request(method = '', url = '', data = {}, header = {}) {// 參數配置url = this.isProtocol(url) ? url : this.configure.baseURL + url;header = { ...this.configure.header, ...header };// 設置傳遞的最新數據this.configure.data = data;this.configure.header = header;this.configure.method = method;// 請求攔截this.interceptors.request.before({ ...this.configure });// request請求return new Promise((resolve, reject) => {wx.request({url: url,data: data,header: header,dataType: this.configure.dataType || 'json',responseType: this.configure.responseType || 'text',method: method,success: res => {// 成功攔截器回調if (res && res.statusCode == 200) {this.interceptors.response.success(res);resolve(res);} else {// 錯誤攔截器回調this.interceptors.response.error(res);reject(res);}},fail: err => {// 錯誤攔截器回調this.interceptors.response.error(err);reject(err);}})})} }

二、創建http.js文件

import request from 'request.js'// 創建request實例 const service = request.create({baseURL: 'http://localhost:8080', // 請求后臺api的地址,可以抽離出去 })// request攔截 service.interceptors.request.use(config => {// 每次請求都可以在header中帶參數config.header['token'] = 1234;config.header['my_sessionid'] = 1234;console.log('request-config:', config);return config; })// response攔截 service.interceptors.response.use(response => {console.log('response-success:', response);return response; }, error => {console.log('response-error:', error);return Promise.reject(error); })// 導出 export default service;

三、在小程序js中使用

先引入http.js

import http from 'http.js'

調用http實例中的方法,有get,post, put,delete等

http.post('/api/user/getList', {name: '小明'}).then(res => {console.log('成功數據:', res.data);}).catch(error => {console.log('失敗數據:', error);})

附上小程序基礎框架的目錄結構圖

總結

以上是生活随笔為你收集整理的小程序仿 axios 请求封装的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。