微信小程式學習筆記二(持續更新)---小程式網路請求封裝
阿新 • • 發佈:2018-12-14
寫小程式的你是否已經厭倦了傳送網路請求的wx.request?接著看吧。。。
一、目錄結構
在專案同級目錄下utils資料夾裡新建一個fetch.js檔案,(名字看自己喜好)
二、直接上程式碼
// 定義網路請求API地址 const baseURL = 'http://yourbaseURL' // 封裝網路請求開始 const http = ({ url, data, method, ...other } = {}) => { let sessionKey = wx.getStorageSync('token') // 以同步方式獲取token避免非同步操作出現延遲錯誤,具體可根據自己專案情況而定 // 我這裡需要在除了登入後的所有介面拼接token,因此判斷了url是否為登入介面由此新增不同的url拼接方式,具體可根據業務邏輯完善程式碼 var requestUrl = '' if (url === '/login/wxLogin') { requestUrl = baseURL + url } else { requestUrl = baseURL + url + "?sessionKey=" + sessionKey } // 新增請求載入等待 wx.showLoading({ title: '載入中...' }) // Promise封裝處理 return new Promise((resolve, reject) => { wx.request({ // 請求地址拼接 url: requestUrl, data: data, // 獲取請求頭配置 header: { 'content-type': 'application/x-www-form-urlencoded' }, method: method, ...other, // 成功或失敗處理 complete: (res) => { // 關閉等待 wx.hideLoading() console.log(res) // // 進行狀態碼判斷並處理,退出登入 if (res.data.code === 8888) { wx.navigateTo({ url: '/pages/login/login', }) } else if (res.data.code !== 0) { // 獲取後臺返回報錯資訊 let title = res.data.msg // 呼叫全域性toast方法 showToast(title) } else if (res.data.code === 0) { resolve(res) } else { reject(res) } } }) }) } // 新增請求toast提示 const showToast = title => { wx.showToast({ title: title, icon: 'none', duration: 1500, mask: true }); } // 進行url字串拼接 const getUrl = url => { if (url.indexOf('://') == -1) { url = baseURL + url } return url } // 重構請求方式 const _fetch = (content) => { return http({ url: content.url, data: content.data, method: content.method }) } module.exports = { baseURL, _fetch, showToast }
三、使用:
1、檔案最上面引入:
let api = require('../../utils/fetch.js')
2、使用
api._fetch({
url: '/yourURL',
data: {yourData},
method: 'get/post....'
}).then((res) => {
// 請求成功後的處理
console.log(res.data)
......
})
注意 1、promise為非同步請求,在fetch.js中使用wx.getStorage獲取token時,會比請求慢一步,因此會出現所取的token值有問題。小程式中在使用promise時使用同步