原创文章,作者:stark,如若转载,请注明出处:https://shudong.wang/10231.html
给大家提供思路,可以借鉴哈,有什么问题可以留言
taro脚手架后面文章会慢慢讲解更多技巧
https://github.com/wsdo/taro-...
为什么封装
当我们开发小程序的时候,经常会用到http请求,当然官方已经提供了请求的接口,但是我们每次请求的时候,可能会加上token,每次请求都会加上,如果不封装起来,会相当的麻烦,那么又怎么封装呢?
特性
- 暴露get方法
- 暴露post方法
- post自定义contentType
- 增加配置文件
- token定义
- 添加判断状态,记录异常信息
- 增加异常错误logError日志
- 增加统一日志上报
设计
需要对外暴露接口:get post
参数:url,传输的数据,请求头
这样我们可以很方便的使用了
在/service/下新建立一个api.js
baseOptions 方法
baseOptions(params, method = 'GET') {
let { url, data } = params
let contentType = 'application/x-www-form-urlencoded'
contentType = params.contentType || contentType
const option = {
isShowLoading: false,
url: base + url,
data: data,
method: method,
header: { 'content-type': contentType, 'token': token }, // 默认contentType ,预留token