在小程序开发中,封装和拦截 wx.request
请求可以让你更方便地管理网络请求、处理公共逻辑(如添加认证信息)、统一错误处理以及实现请求/响应的拦截。以下是如何实现这一目标的基本步骤:
封装 wx.request
首先,我们可以创建一个通用的请求方法来封装 wx.request
,以便在整个应用中复用。
// api.js
function request(options) {
// 设置默认值
const defaultOptions = {
method: 'GET',
data: {},
header: {
'content-type': 'application/json' // 默认值
}
};
// 合并用户提供的options与默认值
options = Object.assign({}, defaultOptions, options);
return new Promise((resolve, reject) => {
wx.request({
...options,
success(res) {
resolve(res.data); // 只返回data部分
},
fail(err) {
reject(err);
}
});
});
}
module.exports = {
request,
};
实现请求拦截器
请求拦截器可以在请求发送前对请求进行预处理,例如添加token等认证信息。
// interceptor.js
const api = require('./api');
function requestWithInterceptor(options) {
// 在请求之前做些什么,比如添加token
if (!options.header) {
options.header = {};
}
// 假设我们有一个全局的token存储
const token = wx.getStorageSync('token');
if (token) {
options.header.Authorization = 'Bearer ' + token;
}
return api.request(options);
}
module.exports = {
request: requestWithInterceptor,
};
实现响应拦截器
响应拦截器允许你在接收到服务器响应后进行统一处理,例如判断登录状态、统一错误处理等。
// responseInterceptor.js
const interceptor = require('./interceptor');
function requestWithResponseInterceptor(options) {
return interceptor.request(options).then(response => {
// 对响应数据做点什么
if (response.statusCode === 401) {
// 处理未授权的情况,可能是跳转到登录页面
wx.navigateTo({
url: '/pages/login/login'
});
throw new Error('Unauthorized');
}
return response;
}).catch(error => {
// 错误处理
console.error('Request failed', error);
throw error;
});
}
module.exports = {
request: requestWithResponseInterceptor,
};
使用示例
现在,你可以在你的小程序页面或组件中使用这个经过封装和拦截的请求方法了。
// pages/index/index.js
const api = require('../../utils/responseInterceptor.js');
Page({
onLoad() {
api.request({
url: 'https://example.com/api/data',
method: 'GET'
}).then(data => {
console.log('Success', data);
}).catch(error => {
console.error('Error', error);
});
}
});
通过这种方式,你可以轻松地为你的小程序添加请求和响应拦截,从而更好地控制网络请求的行为,并简化代码维护工作。