小程序仿 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 请求封装相关推荐
- 微信小程序服务器开小差了,微信小程序wx.request请求封装
微信小程序 wx.request RequestTask wx.request(Object object)发起 HTTPS 网络请求. 示例代码 wx.request({ url: 'test.ph ...
- 微信小程序wx.request请求封装,和跨域的解决。
建议把所有请求抽离到不同页面对应的js文件中,可以方便后期的修改和排查问题,小程序请求是通过微信后台来请求我们的后台地址来进行后端映射.你请求的接口实际到微信的后端做了一道映射,微信后端拿到你的 wx ...
- 微信小程序登录及请求封装
整合了获取用户信息/用户手机号/及请求封装 粘贴即用 目录结构 app.js //app.js // const util = require('/utils/util.js') // import ...
- 微信小程序仿抖音视频
微信小程序仿抖音视频 使用轮播图实现视频滑动效果. wxml 部分 <view class="video-contain"><!-- 自定义头部 -->&l ...
- 微信小程序 wx.request 的封装
自学转行到前端也已近两年,也算是简书和掘金的忠实粉丝,但是以前一直惜字如金(实在是胆子小,水平又低),现在我决定视金钱如粪土(就只是脸皮厚了,水平就那样),好了废话不多说,切入主题,最近自己尝试了一下 ...
- 微信小程序仿淘票票之登录注册讲解
微信小程序仿淘票票之登录注册讲解(这也是我学习的第一步嘛) 前言 一.登录以及注册的业务逻辑 二.核心代码 1.register代码 2.login代码 总结 前言 愉快的期末,终于结束了,我准备把程 ...
- 小程序---仿百思不得姐
话不多说,先看效果图 个人觉得先看官方文档,了解它有什么,再开始动手写效果会好点. 小程序文件结构 一个页面由四个文件组成,并且四个文件必须同名 wxml : 页面结构,类似html. wxss : ...
- 微信小程序的网络请求 —— 微信小程序教程系列(14)
网络请求,基本上是必须的环节之一. 小程序提供了wx.request(object),与开发者的服务器实现数据交互的一个很重要的api. 最简单的用法如下(以GET请求为例) <view bin ...
- 仿猫眼php,微信小程序 仿猫眼实现实例代码
微信小程序仿猫眼 实现效果图: movie.js Page({ data: { movies:null, scrollTop : 0, scrollHeight:0 }, onLoad: functi ...
最新文章
- 熟悉常用的Linux操作
- 密码学研究-数字签名
- latex公式对齐_论文中的公式如何对齐
- python变量存为matlab,详解如何在python中读写和存储matlab的数据文件(*.mat)
- 实战:向GitHub提交代码时触发Jenkins自动构建
- Ubuntu 安装 QQ
- 深入理解脚本化CSS系列第五篇——动态样式
- nfc加密卡pm3和pm5区别_为了省门禁卡的钱,买了NFC读卡器,到底值不值
- 企业出口退税申报系统的Sqlite数据库破解及读写
- 光学成像系统的模型及MATLAB仿真
- AI 技术本身的一些优势,比如它能够从大量数据里去总结背后的规律
- C# 如何插入、编辑和删除Excel批注
- python PIL 图像增强
- Gameplay Ingredients
- cad的lisp画线_Lisp CAD 求助高手!怎么通过代码实现连续画直线?
- 4-ipv6基础知识之-邻居发现协议NDP
- sin60度 用计算机,cos60度等于多少啊
- 模拟量采集模块4-20ma0-10v0-5v转rs485modbus 2/4/8/16路电流电压输出输入
- 照片动感影集制作软件哪个好?如何快速制作精美、酷炫的效果?
- 【mysql】drop、truncate和delete的区别
热门文章
- 数据埋点:用户唯一标识
- 计算机辅助管理考试,计算机辅助考试研究
- stm32核心板可以点亮灯吗_STM32库函数点亮LED
- tf.ConfigProto()函数
- 【Python刷题】_9
- LeetCode-链表-142. 环形链表 II
- 云端大数据实战记录-大数据推荐
- 你真的懂redis的数据结构了吗?redis内部数据结构和外部数据结构揭秘
- Java SE 6 新特性: HTTP 增强--转
- 【风控建模】风控分类模型种类(决策、排序)比较与模型评估体系(ROC/gini/KS/lift)