微信小程序-网络封装

直接使用微信wx.requestwx.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) => {
     // 在这里处理请求失败后的逻辑
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容