小程序請求request封裝

const baseUrl = 'https://xxxxxxx.com';
const app = getApp();
const http = ({ url = '', param = {}, ...other } = {}) => {
  var sessionid = wx.getStorageSync('sessionid');//獲取sessionid
  var that = this;
  wx.showLoading({
    title: '加載中..',
    mask: true
  });
  return new Promise((resolve, reject) => {
    wx.request({
      url: getUrl(url),
      data: param,
      header: {
        'content-type': 'application/json', // 默認值 ,另一種是 "content-type": "application/x-www-form-urlencoded"
        'Cookie': sessionid
      },
      ...other,
      complete: (res) => {
        wx.hideLoading();
        console.log(res);
        if (res.statusCode == 403) {//如果返回狀態碼403,將彈出重新授權彈窗
          console.log(res.statusCode);
          wx.showToast({
            title: '請重新授權',
            icon: 'none',
            duration:1500
          });
          app.globalData.isLogin = true;//是否展示重新授權彈窗:true--顯示,false--隱藏
          console.log(app.globalData.isLogin);
        }else if(res.statusCode >= 200 && res.statusCode < 300){
          resolve(res);
        }else{
          reject(res);
        }
      }
    })
  })
}

const getUrl = (url) => {
  if (url.indexOf('://') == -1) {
    url = baseUrl + url;
  }
  console.log(url);
  return url
}
const _get = (url, param = {}) => {
  return http({
    url,
    param
  })
}
const _post = (url, param = {}) => {
  return http({
    url,
    param,
    method: 'post'
  })
}
module.exports = {
  baseUrl,
  _get,
  _post
}

我自己封裝了個彈窗授權的組件,如需要請留言。

//調用方式
wx.showLoading({
	title: '加載中..',
	mask: true
});
api._get(
	'/xxxxxxxxxx/xxxx/',
	{id:id}
	).then((res)=>{
		console.log(res)	
	}
	wx.hideLoading();
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章