当前位置:网站首页>微信小程序请求封装
微信小程序请求封装
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);
},
结果:
提示:文章到此结束,文章仅为个人学习记录,若有不足还请大家指出。
边栏推荐
- Electromagnetic compatibility introductory tutorial (6) test project
- Explosive 30,000 words, the hardest core丨Mysql knowledge system, complete collection of commands [recommended collection]
- Practical training Navicat Chinese and English mode switching
- Three aspects of Ali: How to solve the problem of MQ message loss, duplication and backlog?
- Leetcode第 304 场周赛
- Golang: go static file processing
- 自制一款远程控制软件——VeryControl
- Information system project managers must recite the work of the core test site (56) Configuration Control Board (CCB)
- 太厉害了,终于有人能把文件上传漏洞讲的明明白白了
- Offer brush questions - 1
猜你喜欢

Guest brush SQL - 2

【HDLBits 刷题】Circuits(1)Combinational Logic

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

支付宝如何生成及配置公钥证书

Golang: go open web service

curl (7) Failed connect to localhost8080; Connection refused

matlab simulink 粒子群优化模糊pid控制的电机泵

Using FiddlerScript caught poly FiddlerScript 】 【 download

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

VSCode 快捷键及通用插件推荐
随机推荐
图片无损压缩软件哪个好用:试试完全免费的JPG-C 图片批量修整压缩减肥工具吧 | 最新jpg批量修整工具下载
零代码网站开发利器:WordPress
配置我的kitty
sum of special numbers
Dell PowerEdge Server R450 RAID Configuration Steps
从零开始—仿牛客网讨论社区项目(一)
Guest brush SQL - 2
从底层结构开始学习FPGA(6)----分布式RAM(DRAM,Distributed RAM)
Compare two objects are the same depth
2022杭电多校第二场1011 DOS Card(线段树)
爬虫框架 Scrapy 详解
对于升级go1.18的goland问题
我三本学历,五面阿里,被面试官“供”着出来了,拿了33*15的Offer
rhcsa 第四天
13 - JUC CountDownLatch concurrent programming
我的创作纪念日
The Bean's life cycle
如何使用Photoshop合成星轨照片,夜空星轨照片后期处理方法
GO错误处理方式
LevelSequence源码分析