美文网首页微信小程序
微信小程序-对request的封装

微信小程序-对request的封装

作者: hello_web_Front | 来源:发表于2020-08-12 16:53 被阅读0次

    这里我只是对wx-request进行了封装 如果你需要对全局的api进行封装 参考:https://developers.weixin.qq.com/miniprogram/dev/extended/utils/api-promise.html

    request.js promise 化

    const baseUrl = "http://192.168.x.xx:18088/api/";
    const app = getApp();
    // 把请求包装成promise请求的方式
    export default function (url, type, parmas, header) {
       const acc_token = wx.getStorageSync("token")||null;
       return new Promise((resolve, reject) => {
         在这加上全局的loadding
           if(app.globalData.language=='cn'){
               wx.showLoading({
                   title: '加载中',
               })
           }else{
              
               wx.showLoading({
                   title: 'Loading',
               })
           }
         
           wx.request({
               url: baseUrl + url,
               data: parmas || {},
               // 如果是表单提交 给我传的content-type为 application/x-www-form-urlencoded
               // 文件的上传 content-type 设置为multipart/form-data
               header:  {
                   'content-type': 'application/json',
                   "Authorization":'Bearer '+acc_token
    
               },
               method: type || 'POST',
               success: (result) => {
    
                   if (result.statusCode == 200) {
                       
                       resolve(result.data.result,'ok');
                   } else if(result.statusCode == 401){
                       resolve('当前没有登陆')
                   }
                   else {
                       // 说明是其他类型的错误
                       console.log('请求失败!当前的状态码为:', result.statusCode);
                   }
               },
               fail: (err) => {
                   reject(err);
               },
               complete: () => {
                   setTimeout(function () {
                       wx.hideLoading()
                   })
               }
           });
       })
    }
    

    使用:

    import request from '../../request/request'
    const data = await request("ExpenseType/getAllExpenseType", 'POST')

    就可以啦。

    相关文章

      网友评论

        本文标题:微信小程序-对request的封装

        本文链接:https://www.haomeiwen.com/subject/csrmdktx.html