寫小程序的你是否已經厭倦了發送網絡請求的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時使用同步的方式獲取token--**wx.getStorageSync('token') **
2、大多數業務並非選擇url拼接token的方式發送請求,而是將token存入header中一並帶入,示例 點擊這里