博客
关于我
如何使用Promise封装wx.request()
阅读量:615 次
发布时间:2019-03-13

本文共 1824 字,大约阅读时间需要 6 分钟。

套件开发指南:基于WX小程序的API请求体系构建

一、项目结构规划

建立一个完整的 requester 系统,通过封装 wx.request 实现多种 HTTP 请求方式的统一处理。系统将包含以下核心文件:

  • /api:存储接口定义文件。
  • /fetch:封装 wx.request 提供 Promise 接口。
  • /http:处理 HTTP 请求,支持多种 HTTP 方法。
  • /config: 接口配置中心,维护公共参数和接口......

二、基础库开发

1. Fetch 接口封装

/fetch 文件中,创建一个通用处理 wx.request 的 Promise 接口。

// /fetch/index.jsconst fetchRequest = (url, method, data) => {    return new Promise((resolve, reject) => {        wx.request({            url,            method,            data: Object.assign({}, data),            header: {                'Content-Type': 'application/text'            },            success(res) {                resolve(res);            },            fail(err) {                reject(err);            }        });    });};module.exports = fetchRequest;
2. 接口管理

将具体接口路径定义在 /api 文件中,例如:

// /api/api.jsexport const ApiConfig = {    /!* 接口例 */: '/service/example'};

三、HTTP 请求处理

1. 基础配置

/http 文件中设置基础配置参数,并引入 fetch 工作工具。

// /http/http.jsconst fetchUtils = require('./fetch');const config = {    baseUrl: 'https://api.example.com', // )))};export const http = {    // 常用方法定义...}
2. 请求方法封装

根据不同 HTTP 方法定义对应的请求方式:

// /http/http.jshttp_get = (path, data) => {    return fetchUtils(`${config.baseUrl}${path}`, 'GET', data);};http_post = (path, data) => {    return fetchUtils(`${config.baseUrl}${path}`, 'POST', data);};
3. 异常处理

统一处理请求过程中的异常情况:

// global handled in http.jsconst handleError = (err) => {    console.error('请求失败:', err);    // 可选:跳转错误页面或其他处理};

四、应用实例

在全局 app.js 中注册 HTTP 工作单元,并在各页面中使用:

// global.jsconst http = require('./http/http');Vue.prototype.http = http;
使用示例

在页面组件中:

onLoad() {    this.http.banner() // 调用 HTTP 实现的 banner 方法        .then(res => {            this.list = res.data.list;        })        .catch(err => {            handleError(err);        });}

通过以上方案,可以快速构建一个灵活且可维护的 HTTP 请求体系,适用于多种复杂场景。

转载地址:http://qhtaz.baihongyu.com/

你可能感兴趣的文章
npm前端包管理工具简介---npm工作笔记001
查看>>
npm包管理深度探索:从基础到进阶全面教程!
查看>>
npm升级以及使用淘宝npm镜像
查看>>
npm发布包--所遇到的问题
查看>>
npm发布自己的组件UI包(详细步骤,图文并茂)
查看>>
npm和package.json那些不为常人所知的小秘密
查看>>
npm和yarn清理缓存命令
查看>>
npm和yarn的使用对比
查看>>
npm如何清空缓存并重新打包?
查看>>
npm学习(十一)之package-lock.json
查看>>
npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
查看>>
npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
查看>>
npm安装教程
查看>>
npm报错Cannot find module ‘webpack‘ Require stack
查看>>
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>