当前位置:网站首页>Wechat applet wx Request request encapsulation
Wechat applet wx Request request encapsulation
2022-06-26 12:27:00 【C+ Ankou wood】
The way 1:
// utils/wxAjax.js
const baseUrl = 'https://*****/';// Here, you can obtain different domain names through the environment variables
// Encapsulation request
module.exports = function (options) {
return new Promise((resolve, reject) => {
wx.showLoading({
title: ' Loading ',
});
wx.request({
url: baseUrl + options.url,
method:
options.method === 'GET' ? options.data : JSON.stringify(options.data),
data: options.data,
header: {
'content-type': 'application/json',
// 'x-token': 'x-token'
},
success: function (res) {
resolve(res);
// Status judgment can be added here
},
fail: function (error) {
reject(error);
},
complete: () => {
setTimeout(() => {
wx.hideLoading();
}, 100);
},
});
});
};
Use :
// Use on other pages import request from '../utils/wxAjax'
// Further encapsulation -1.js
export const QUERY_USER_INFO=(data = {
})=> {
return request({
// baseURL: hostConfig.xxx,
url: "/api/user/info",
method: "GET",
data,
});
},
// Use -2.js
import {
QUERY_USER_INFO } from 'xxx'
QUERY_USER_INFO({
a:1}).then(res => {
if(){
}
}).catch(err => {
wx.showToast({
title: err.message,
})
})
Mode two :
Create in applet directory api Folder , And create... In the folder api.js Script . Now start packaging wx.request
const app = getApp()
const request = (url, options) => {
return new Promise((resolve, reject) => {
wx.request({
url: `${
app.globalData.host}${
url}`,
method: options.method,
data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
header: {
'Content-Type': 'application/json; charset=UTF-8',
},
success(request) {
if (request.data.code === 2000) {
resolve(request.data)
} else {
reject(request.data)
}
},
fail(error) {
reject(error.data)
}
})
})
}
const get = (url, options = {
}) => {
return request(url, {
method: 'GET', data: options })
}
const post = (url, options) => {
return request(url, {
method: 'POST', data: options })
}
const put = (url, options) => {
return request(url, {
method: 'PUT', data: options })
}
// Cannot declare DELETE( keyword )
const remove = (url, options) => {
return request(url, {
method: 'DELETE', data: options })
}
module.exports = {
get,
post,
put,
remove
}
Use encapsulated api
import api from '../api/api'
api.post('/api/user/info', {
data: ''
}).then(res => {
console.log(res)
}).catch(err => {
wx.showToast({
title: err.message,
})
})
post The request is api.post()…,get The request is api.get()…
Mode three :
get Just send the request directly ,post request JSON.stringify(data) once
const baseURL = 'https://some-domain.com/api/';
let header = {
'content-type': 'application/json'};
function request(method, url, data) {
return new Promise(function(resolve, reject) {
wx.request({
url: baseURL + url,
method: method,
data: method === POST ? JSON.stringify(data) : data,
header: header,
success(res) {
// The request is successful
// Judge status code ---errCode The status is determined according to the backend definition
if (res.data.errCode == 0) {
resolve(res);
} else {
// Other anomalies
reject(' Runtime error , Please try again later ');
}
},
fail(err) {
// request was aborted
reject(err)
}
})
})
}
Use :
1, In a small program util New under folder api.js, And put the above code in and create the request , And export
// Import request after
const API = {
getOpenid: (data) => request(GET, `jsapi/mini?jsCode=${
data}`),
};
module.exports = {
API: API,
// xxx,
}
2, Here we get openid Interface, for example
stay .js Introduce... Into the document api.js Under the API
const $api = require('../../utils/api.js').API;
Page({
data: {
},
onLoad: function (options) {
wx.login({
success:res=> {
// Call interface get openid
$api.getOpenid(res.code)
.then(res => {
// The request is successful
})
.catch(err => {
// request was aborted
})
}
})
}
})
边栏推荐
- NFS共享存储服务安装
- 2022 edition of investment analysis and "fourteenth five year plan" development prospect forecast report of China's switchgear industry
- On the use of protostaff [easy to understand]
- 证券账户可以开通 开户安全吗
- 环形队列php
- Current situation investigation and investment prospect forecast analysis report of China's electrolytic copper market from 2022 to 2028
- HUST network attack and defense practice | 6_ IOT device firmware security experiment | Experiment 3 freertos-mpu protection bypass
- Analysis report on the "fourteenth five year plan" and investment prospect of China's pharmaceutical equipment industry 2022-2028
- 2022 edition of China's cotton chemical fiber printing and dyeing Market Status Investigation and Prospect Forecast Analysis Report
- 【Redis 系列】redis 学习十六,redis 字典(map) 及其核心编码结构
猜你喜欢
1、 MySQL introduction
JMeter response time and TPS listener tutorial
PHP laravel+gatewayworker completes im instant messaging and file transfer (Chapter 1: basic configuration)
AD - 将修改后的 PCB 封装更新到当前 PCB 中
leetcode 715. Range module (hard)
TP5 thinkphp5 report serialization of'closure'is not allowed
11、 Box styles and user interface
2021 q3-q4 investigation report on the use status of kotlin multiplatform
Omnichannel membership - tmall membership 1: opening tutorial
New routing file in laravel framework
随机推荐
HUST網絡攻防實踐|6_物聯網設備固件安全實驗|實驗二 基於 MPU 的物聯網設備攻擊緩解技術
Scala-day06- pattern matching - Generic
VMware虚拟机 桥接模式 无法上网 校园网「建议收藏」
Leetcode 78. Subset and 90 Subset II
Report on in-depth analysis and investment strategy recommendations for China's petroleum coke industry (2022 Edition)
Examples of how laravel uses with preload (eager to load) and nested query
UDP协议详解[通俗易懂]
Redis cannot connect to the server through port 6379
Xiaolong 888 was released, Xiaomi 11 was launched, and 14 manufacturers carried it in the first batch!
Demand scale forecast and investment competitiveness analysis report of China's new material market 2022-2028
Polarismesh series articles - concept series (I)
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure
How can we reach members more effectively?
Omni channel member link - tmall member link 3: preparation of member operation content
Scala-day03- operators and loop control
Which is safer and better for great wisdom to open an account
File decryption in webgame development
How long ago did PHP get
7-16 货币系统Ⅰ
VMware virtual machine bridging mode can not access the campus network "suggestions collection"