当前位置:网站首页>微信小程序请求封装
微信小程序请求封装
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);
},
结果:
提示:文章到此结束,文章仅为个人学习记录,若有不足还请大家指出。
边栏推荐
- How to generate and configure public key certificate in Alipay
- Golang: go get url and form attribute value
- mysql中添加字段的相关问题
- 「面经分享」西北大学 | 字节 生活服务 | 一面二面三面 HR 面
- Why is the lightweight VsCode used more and more?Why eat my C drive 10G?How to Painlessly Clean VsCode Cache?Teach you how to lose weight for C drive
- 仿牛客网项目总结
- Dart exception details
- 监听父元素宽高,自适应插件大小
- weight distribution
- 配置我的kitty
猜你喜欢

crypto-js uses

MATLAB程序设计与应用 2.5 MATLAB运算

数据机构----线性表之单向链表

响应式织梦模板园林景观类网站

如何使用Photoshop合成星轨照片,夜空星轨照片后期处理方法

How JS works

sum of special numbers

datagrip 报错 “The specified database userpassword combination is rejected...”的解决方法

"By sharing" northwestern university life service | | bytes a second interview on three sides by HR

零代码网站开发利器:WordPress
随机推荐
Win任务栏图标异常解决
Monitor the width and height of the parent element, adapt to the size of the plug-in
The use of Golang: go template engine
datagrip 报错 “The specified database userpassword combination is rejected...”的解决方法
【视觉SLAM十四讲】第一章理论详解
Golang:go模版引擎的使用
电磁兼容简明教程(6)测试项目
Golang:go连接和使用mysql
Leetcode第 304 场周赛
Dart exception details
Offer brush questions - 1
我说过无数遍了:从来没有一种技术是为灵活组合这个目标而设计的
Why is the lightweight VsCode used more and more?Why eat my C drive 10G?How to Painlessly Clean VsCode Cache?Teach you how to lose weight for C drive
响应式织梦模板园林花卉类网站
POJ2421道路建设题解
my creative day
NIO programming
The Bean's life cycle
05-SDRAM:仲裁
Guest brush SQL - 2