微信小程序request请求封装
// request.js (最基本封装)
function request(url, data = {}, method = 'GET') {
return new Promise((resolve, reject) => {
wx.showLoading({
title: '加载中...'
});
wx.request({
url: 'https://example.com' + url,// 假设服务器地址前缀为https://example.com
data: data,
method: method,
header: {
'Content-Type': 'application/json'
},
success: (res) => {
wx.hideLoading();
if (res.statusCode === 200) {
resolve(res.data);
} else {
reject(new Error('请求失败,状态码:' + res.statusCode));
}
},
fail: (err) => {
wx.hideLoading();
reject(new Error('网络请求失败:' + err.errMsg));
}
});
});
}
export default request;
// request.js(可以在请求发送前对请求进行一些处理,如添加 token)
function request(url, data = {}, method = 'GET') {
return new Promise((resolve, reject) => {
const token = wx.getStorageSync('token');
wx.showLoading({
title: '加载中...'
});
wx.request({
url: 'https://example.com' + url,
data: data,
method: method,
header: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
success: (res) => {
wx.hideLoading();
if (res.statusCode === 200) {
resolve(res.data);
} else {
reject(new Error('请求失败,状态码:' + res.statusCode));
}
},
fail: (err) => {
wx.hideLoading();
reject(new Error('网络请求失败:' + err.errMsg));
}
});
});
}
// request.js (可以在响应返回后对数据进行处理,如统一处理错误信息)
function request(url, data = {}, method = 'GET') {
return new Promise((resolve, reject) => {
const token = wx.getStorageSync('token');
wx.showLoading({
title: '加载中...'
});
wx.request({
url: 'https://example.com' + url,
data: data,
method: method,
header: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
success: (res) => {
wx.hideLoading();
if (res.statusCode === 200) {
if (res.data.code === 0) {
resolve(res.data.data);
} else {
wx.showToast({
title: res.data.msg,
icon: 'none'
});
reject(new Error(res.data.msg));
}
} else {
reject(new Error('请求失败,状态码:' + res.statusCode));
}
},
fail: (err) => {
wx.hideLoading();
reject(new Error('网络请求失败:' + err.errMsg));
}
});
});
}
假设你在utils目录创建的request.js文件,基本使用如下:
// pages/index/index.js
import request from '../../utils/request.js';
Page({
async getData() {
try {
const res = await request('/api/list', { page: 1, limit: 10 }, 'GET');
console.log(res);
} catch (error) {
console.error(error);
}
},
onLoad: function() {
this.getData();
}
});
总之封装完,代码简洁复用性高,也非常 利于 使用 async await 将异步变更同步代码