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

你可能感兴趣的文章
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>