博客
关于我
如何使用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/

你可能感兴趣的文章
PAT (Basic Level) Practice 乙级1051-1055
查看>>
PAT (Basic Level) Practise - 写出这个数
查看>>
PAT 1027 Colors in Mars
查看>>
PAT 1127 ZigZagging on a Tree[难]
查看>>
PAT 2-07. 素因子分解(20)
查看>>
PAT A1033 重点题
查看>>
SparkSQL学习03-数据读取与存储
查看>>
PAT L2-012. 关于堆的判断
查看>>
PAT Spell It Right [非常简单]
查看>>
PAT-1044. Shopping in Mars (25)
查看>>
PAT-乙级-1040 有几个PAT
查看>>
pat1011. World Cup Betting (20)
查看>>
Spring组件扫描配置
查看>>
PAT1093 Count PAT's (25)(逻辑题)
查看>>
PATA1038题解(需复习)
查看>>
Patching Array
查看>>
Spring源码学习(二):Spring容器之prepareContext和BeanFactoryPostProcessor的介绍
查看>>
PatchMatchStereo可能会需要的Rectification
查看>>
Path does not chain with any of the trust anchors
查看>>
Path形状获取字符串型变量数据
查看>>