当前位置:网站首页>微信小程序请求封装
微信小程序请求封装
2022-08-01 07:10:00 【大橘为重¨】
前言
官方文档提供微信小程序发送请求的方法有wx.request,但每次发送请求都调用该接口会十分不便于接口的管理。所以通过封装请求的方法来对接口进行集中式控制管理,简化代码的维护流程。
文章使用的案例文件结构:
1、封装网络请求
创建 “request.js” 文件如下:
const baseUrl = "https://www.xxxxx.xxx/xxx"
let token = wx.getStorageSync('token')
// 参数 "options" 从接口函数传递过来
const request = (options) => {
return new Promise((resolve,reject) => {
// 拼接请求地址
options.url = baseUrl + options.url
wx.request({
// 配置 "wx.request" 请求参数
...options,
header: {
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Cookie':wx.getStorageSync('cookieKey'), // 配置传递Cookie(微信小程序默认没有cookie,如有需要可以自己储存下来再从请求头传递给后端)
'token':`${
token}`
},
success: function (res) {
console.log("network-res=>", res);
// 记录 Cookie,以便下一个请求传递
wx.setStorageSync("cookieKey", res.header["Set-Cookie"]);
// 返回成功信息
resolve(res.data)
},
fail: function (error) {
console.log("network-err=>", error);
// 返回错误信息
reject(error)
}
})
})
}
export default request
2、编写接口函数
创建 “test.js” 文件如下:
import request from './request.js'
// 接口测试
export function testNetwork() {
return request({
url: `/slides`,
method: 'GET'
})
}
3、调用接口函数
再 “页面js文件” 中导入需要的接口函数:
import {
testNetwork } from "../../network/test";
使用该方法进行测试:
async onLoad(options) {
let {
data:res} = await testNetwork()
console.log("res=>",res);
},
结果:
提示:文章到此结束,文章仅为个人学习记录,若有不足还请大家指出。
边栏推荐
- 【HDLBits 刷题】Circuits(1)Combinational Logic
- POJ2421道路建设题解
- Fist game copyright-free music download, League of Legends copyright-free music, can be used for video creation, live broadcast
- Golang: go open web service
- 配置我的kitty
- Golang:go模版引擎的使用
- Does flinkcdc have any solution for mysql's date field type conversion?
- 支付宝如何生成及配置公钥证书
- Data organization -- singly linked list of the linear table
- 基于百度OCR的网站验证码在线识别
猜你喜欢
随机推荐
Explosive 30,000 words, the hardest core丨Mysql knowledge system, complete collection of commands [recommended collection]
Upgrade to heavyweight lock, lock reentrancy will lead to lock release?
Win任务栏图标异常解决
Datagrip error "The specified database userpassword combination is rejected..."Solutions
点餐系统数据库设计--SQL Server
Introduction to the basic principles, implementation and problem solving of crawler
响应式织梦模板园林景观类网站
crypto-js uses
数据机构----线性表之单向链表
JVM:运行时数据区-PC寄存器(程序计数器)
金山打字通 官网 下载
datagrip 报错 “The specified database userpassword combination is rejected...”的解决方法
Vim扩展内容
Zero-code website development tool: WordPress
企业员工人事管理系统(数据库课设)
Detailed explanation of the crawler framework Scrapy
我三本学历,五面阿里,被面试官“供”着出来了,拿了33*15的Offer
More than 2022 cattle guest school game 4 yue
MATLAB程序设计与应用 2.5 MATLAB运算
05-SDRAM:仲裁









