直接使用微信wx.request
和wx.uploadFile
会让代码看起来有点繁琐,所以一般都进行一次封装,方便外面打点调用:
const apiHost = 'https://xxx/'
export function appRequest(path, data, method = 'GET') {
let requestUrl = apiHost + path
// console.log('请求参数:',JSON.stringify(data))
return new Promise((resolve, reject) => {
wx.request({
url: requestUrl,
header: getApp().globalData.requestHeader,
data: data,
method: method,
success: (res) => {
// console.log('request success:'+JSON.stringify(res));
resolve(res.data); // 请求成功时,将结果通过 resolve 返回
},
fail: (err) => {
reject(err); // 请求失败时,通过 reject 返回错误信息
}
});
});
}
export function appUpload(path, fileTempPath, key) {
let requestUrl = apiHost + path
return new Promise((resolve, reject) => {
wx.uploadFile({
url: requestUrl, // 服务器接口的 URL
filePath: fileTempPath,
name: key, // 服务器接收文件的字段名
header: getApp().globalData.requestHeader,
success: function (uploadRes) {
resolve(uploadRes.data);
},
fail: function (error) {
reject(error);
}
});
})
}
module.exports = {
appRequest,
appUpload
};
这样封装后,在外面就可以像下面这样方便的调用了:
import { appRequest, appUpload } from './utils/api.js';
appRequest('eggs/unlock', { eggId: eggItem.id }, 'GET')
.then((res) => {
// 在这里处理请求成功后的逻辑
})
.catch((error) => {
// 在这里处理请求失败后的逻辑
});
appUpload('oss/upload/img', tempFilePath, 'img').then((res) => {
// 在这里处理请求成功后的逻辑
})
.catch((error) => {
// 在这里处理请求失败后的逻辑
});