微信小程序 HTTP 请求封装
下面是一个完整的微信小程序 HTTP 请求工具封装,支持 GET、POST 等请求方法,可以传递参数,并包含请求拦截、响应拦截、错误处理等功能。
1. 创建 http.js 工具文件
在 utils
目录下创建 http.js
文件:
// utils/http.js
const BASE_URL = 'https://your-api-domain.com/api'; // 替换为你的API基础地址
/**
* 微信小程序HTTP请求封装
* @param {string} method 请求方法 GET/POST/PUT/DELETE
* @param {string} url 请求地址
* @param {object} data 请求参数
* @param {object} header 请求头
* @param {boolean} showLoading 是否显示加载提示
* @returns {Promise}
*/
const request = (method, url, data = {}, header = {}, showLoading = true) => {
// 显示加载提示
if (showLoading) {
wx.showLoading({
title: '加载中...',
mask: true
});
}
// 请求拦截:可以在这里添加token等全局参数
const token = wx.getStorageSync('token');
if (token) {
header['Authorization'] = `Bearer ${token}`;
}
// 返回Promise
return new Promise((resolve, reject) => {
wx.request({
url: `${BASE_URL}${url}`,
method: method,
data: data,
header: {
'Content-Type': 'application/json',
...header
},
success: (res) => {
// 响应拦截:根据业务需求处理响应数据
if (res.statusCode === 200) {
// 这里可以根据你的API返回结构进行调整
if (res.data.code === 0 || res.data.success) {
resolve(res.data);
} else {
// 业务逻辑错误
wx.showToast({
title: res.data.message || '请求失败',
icon: 'none'
});
reject(res.data);
}
} else {
// HTTP状态码错误处理
handleHttpError(res.statusCode);
reject(res);
}
},
fail: (err) => {
// 网络错误处理
wx.showToast({
title: '网络错误,请稍后重试',
icon: 'none'
});
reject(err);
},
complete: () => {
if (showLoading) {
wx.hideLoading();
}
}
});
});
};
// HTTP错误状态码处理
function handleHttpError(statusCode) {
const errorMessages = {
400: '请求参数错误',
401: '未授权,请重新登录',
403: '拒绝访问',
404: '请求资源不存在',
500: '服务器错误',
502: '网关错误',
503: '服务不可用',
504: '网关超时'
};
const message = errorMessages[statusCode] || `请求失败,状态码: ${statusCode}`;
wx.showToast({
title: message,
icon: 'none'
});
// 如果是401未授权,跳转到登录页
if (statusCode === 401) {
wx.navigateTo({
url: '/pages/login/login'
});
}
}
// 封装常用方法
const http = {
get: (url, data, header, showLoading) => request('GET', url, data, header, showLoading),
post: (url, data, header, showLoading) => request('POST', url, data, header, showLoading),
put: (url, data, header, showLoading) => request('PUT', url, data, header, showLoading),
delete: (url, data, header, showLoading) => request('DELETE', url, data, header, showLoading),
upload: (url, filePath, formData = {}, name = 'file') => {
return new Promise((resolve, reject) => {
wx.uploadFile({
url: `${BASE_URL}${url}`,
filePath: filePath,
name: name,
formData: formData,
header: {
'Authorization': `Bearer ${wx.getStorageSync('token')}`
},
success: (res) => {
if (res.statusCode === 200) {
try {
const data = JSON.parse(res.data);
resolve(data);
} catch (e) {
resolve(res.data);
}
} else {
handleHttpError(res.statusCode);
reject(res);
}
},
fail: (err) => {
wx.showToast({
title: '上传失败',
icon: 'none'
});
reject(err);
}
});
});
}
};
// 导出
export default http;
2. 使用示例
GET 请求示例
import http from '../../utils/http';
// 不带参数
http.get('/user/info')
.then(res => {
console.log('获取用户信息成功', res);
})
.catch(err => {
console.error('获取用户信息失败', err);
});
// 带参数
http.get('/products', { category: 'electronics', page: 1 })
.then(res => {
console.log('获取产品列表成功', res);
});
POST 请求示例
import http from '../../utils/http';
// 提交数据
http.post('/user/login', {
username: 'admin',
password: '123456'
})
.then(res => {
console.log('登录成功', res);
// 存储token
wx.setStorageSync('token', res.data.token);
})
.catch(err => {
console.error('登录失败', err);
});
// 自定义请求头
http.post(
'/some-api',
{ key: 'value' },
{ 'X-Custom-Header': 'custom-value' }
);
文件上传示例
import http from '../../utils/http';
// 选择文件
wx.chooseImage({
success(res) {
const tempFilePaths = res.tempFilePaths;
http.upload('/upload', tempFilePaths[0], { description: '图片描述' })
.then(res => {
console.log('上传成功', res);
});
}
});
3. 功能特点
- 基础功能:
- 支持 GET、POST、PUT、DELETE 等请求方法
- 自动处理请求头和基础 URL
- 支持显示/隐藏加载提示
- 拦截器功能:
- 请求拦截:自动添加 token 等认证信息
- 响应拦截:统一处理业务逻辑错误
- 错误处理:统一处理 HTTP 错误状态码
- 扩展功能:
- 文件上传封装
- 401 自动跳转登录页
- 可配置是否显示加载提示
- 易用性:
- Promise 风格 API
- 清晰的错误提示
- 类型明确的返回结果
这个封装可以满足大多数小程序项目的 HTTP 请求需求,你可以根据实际项目需求进一步调整或扩展。