本文共 1824 字,大约阅读时间需要 6 分钟。
建立一个完整的 requester 系统,通过封装 wx.request 实现多种 HTTP 请求方式的统一处理。系统将包含以下核心文件:
/api:存储接口定义文件。/fetch:封装 wx.request 提供 Promise 接口。/http:处理 HTTP 请求,支持多种 HTTP 方法。/config: 接口配置中心,维护公共参数和接口......在 /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; 将具体接口路径定义在 /api 文件中,例如:
// /api/api.jsexport const ApiConfig = { /!* 接口例 */: '/service/example'}; 在 /http 文件中设置基础配置参数,并引入 fetch 工作工具。
// /http/http.jsconst fetchUtils = require('./fetch');const config = { baseUrl: 'https://api.example.com', // )))};export const http = { // 常用方法定义...} 根据不同 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);}; 统一处理请求过程中的异常情况:
// 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/