当前位置:网站首页>Wechat applet request encapsulation
Wechat applet request encapsulation
2022-04-23 06:35:00 【Fan Ke】
Preface
As long as it's the front end , No matter what framework or language , Can't avoid requesting data from the server , The following is provided by wechat applet APIwx.request
wx.request({
url: 'www.baidu.com', // Just for the sample , Not a real interface address
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // The default value is
},
success (res) {
console.log(res.data)
}
});
To improve development efficiency , Encapsulation can make the development process more lively .
Realization
Generally, it is selected under the external root directory , establish utils
Folder ,utils
Create under folder http.js
utils/http.js
http.js
const baseURL = app.globalData.baseURL; // stay app.js Of globalData Add in baseURL
function get(url, param, callback) {
// load Prompt box , You can customize
wx.showLoading({
title: " Loading ...",
mask: true,
});
wx.request({
url: baseUrl + url, // Basic routing + The address sent
data: param,
header: {
"content-type": "application/json", // The default value is
openid: wx.getStorageSync('wxOpenId') // Add in the interface openid, Be similar to token
},
success: function success(res) {
wx.hideLoading(); // hide load box
// The following is the response interception , give an example , According to the status code given by the back end , Make a simple interception here
if (res.data.code == 255) {
wx.showModal({
content: " Need to log in ",
success(res) {
if (res.confirm) {
wx.navigateTo({
url: "../../loginInfo/login/login",
});
} else if (res.cancel) {
wx.navigateBack();
}
},
});
} else {
// Callback after success
callback(res.data);
}
},
});
}
// and get Empathy
function post(url, param, callback) {
wx.showLoading({
title: " Loading ...",
mask: true,
});
wx.request({
url: baseUrl + url, // Just for the sample , Not a real interface address
data: param,
method: "POST",
header: {
"content-type": "application/json", // The default value is
openid: wx.getStorageSync('wxOpenId')
},
success: function success(res) {
wx.hideLoading();
if (res.data.code == 255) {
wx.showModal({
content: " Need to log in ",
success(res) {
if (res.confirm) {
wx.navigateTo({
url: "../../loginInfo/login/login",
});
} else if (res.cancel) {
wx.navigateBack();
}
},
});
} else {
callback(res.data);
}
},
});
}
// Get page path
function getUrl() {
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const url = `/${
currentPage.route}`;
console.log(url);
wx.setStorage({
key: "Url",
data: url,
});
}
module.exports = {
get,
post,
getUrl
};
- Usually used more mainly or
get
andpost
, So it encapsulates two , If there are more , You can extract the contents separately , Then defineput
、delete
Other methods - Or directly add the fourth formal parameter , The default is for
get
, It's just that it's more troublesome , Every request is notget
All interfaces have to pass parameters once , Look at their needs
app.js
stay
app.js
Data defined in , It's kind of likeconfig.js
The feeling of , Configure online address , Local address , And the address of the picture mosaic
globalData: {
baseUrl: 'https://xxx.com/api/', // on-line
//baseUrl: 'http://xxx.com/api/', // Local
imgUrl: 'https://xxx.com/img/', // Picture splicing address
}
The actual use
stay
app.js
The head of
var http = require("utils/http.js");
App({
http,
showToast(title) {
wx.showToast({
title: title,
icon: "none",
duration: 2000,
mask: true,
});
},
globalData: {
baseUrl: 'https://xxx.com/api/', // on-line
//baseUrl: 'http://xxx.com/api/', // Local
imgUrl: 'https://xxx.com/img/', // Picture splicing address
}
});
Use... On the page
const app = getApp();
Page({
/** * Initial data of the page */
data: {
bannerList: [],
},
/** * Life cycle function -- Monitor page loading */
onLoad: function (options) {
this.getBanner();
},
/** * Get the carousel */
getBanner() {
app.http.get("banner/getList", {
}, (res) => {
if (res.code == 1) {
// Look at the picture returned from the back end , Some may need to splice their own paths
res.data.forEach((val, index) => {
val.image = app.globalData.imgUrl + val.image;
});
this.setData({
cuList: res.data,
});
} else {
console.log(res.msg);
}
});
},
});
版权声明
本文为[Fan Ke]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210614037555.html
边栏推荐
- vs中的多字节与unicode
- Solution to the trial of ycu Blue Bridge Cup programming competition in 2021
- Gesture recognition research
- Record the installation and configuration of gestermer on TX2, and then use GST RTSP server
- Generation of verification code
- 进程间通信-互斥锁
- Rust 的 Box指针
- The onnx model of yolov5 removes the transfer layer
- 数组旋转
- 队列解决约瑟夫问题
猜你喜欢
1007 go running (hdu6808) in the fourth game of 2020 Hangzhou Electric Multi school competition
非参数化相机畸变模型简介
[ThreadX] h743zi + lan8720 + ThreadX + netx duo transplantation
大学概率论与数理统计知识点详细整理
Export the articles written in CSDN to PDF format
Import of data
C语言循环结构程序
Addition, deletion, query and modification of data
P1586 solution to tetragonal theorem
Solution to the trial of ycu Blue Bridge Cup programming competition in 2021
随机推荐
利用文件保存数据(c语言)
小区房价可视化
The waterfall waterfall flow of uview realizes single column and loads more
Flask操作多个数据库
Export of data
搭建jpress个人博客
Linux 用rpm的方式安装mysql(超简单)
Type conversion in C #
Rust:单元测试(cargo test )的时候显示 println 的输出信息
定位器
Programmers can also write novels
Rust 的 Box指针
ArcGIS license错误-15解决方法
[leetcode 150] evaluation of inverse Polish expression
GDAL+OGR学习
C#【文件操作篇】PDF文件和图片互相转换
线程和进程的关系和区别是什么
对象数组与对象指针
Class inheritance and derivation
[ThreadX] h743zi + lan8720 + ThreadX + netx duo transplantation