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

你可能感兴趣的文章
php json dom解析
查看>>
ReentrantReadWriteLock读写锁解析
查看>>
php laravel实现依赖注入原理(反射机制)
查看>>
php laravel请求处理管道(装饰者模式)
查看>>
ReentrantReadWriteLock读写锁底层实现、StampLock详解
查看>>
PHP mongoDB 操作
查看>>
ReentrantLock读写锁
查看>>
ReentrantLock的公平锁与非公平锁
查看>>
php mysql procedure获取多个结果集
查看>>
php mysql query 行数,PHP和MySQL:返回的行数
查看>>
php mysql session_php使用MySQL保存session会话
查看>>
PHP mysql_real_escape_string() 函数防SQL注入
查看>>
php mysql优化方法_MySQL优化常用方法
查看>>
PHP OAuth 2.0 Server
查看>>
php odbc驱动,php常用ODBC函数集(详细)
查看>>
php openssl aes ecb,php openssl_encrypt AES-128-ECB iOS
查看>>
php paypal rest api,PayPal REST API指定网络配置文件PHP
查看>>
php pcntl 多进程学习
查看>>
PHP pcntl_fork不能在web服务器中使用的变通方法
查看>>
php private ,public protected三者的区别
查看>>