小程序仿 axios 请求封装
生活随笔
收集整理的這篇文章主要介紹了
小程序仿 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 请求封装的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信小程序签名(横屏+竖屏)
- 下一篇: 微信小程序用wxs实现手机号码用****