Uniapp如何封裝網(wǎng)絡(luò)請求方法demo
更新時間:2023年10月20日 11:58:35 作者:小拼拼
這篇文章主要為大家介紹了Uniapp如何封裝網(wǎng)絡(luò)請求方法demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
引言
寫文章的故事:給整宕機了
第一步:定義請求文件
request.js
import encrypt from '@/util/encrypt'
import {
settings
} from '@/settings.js'
const BASE_URL = settings.BASE_URL
const encryptKey = settings.ENCRYPT_KEY
const whiteList = settings.WHITE_LIST
export const request = (options) => {
const token = uni.getStorageSync('shopToken')
const head = {
'Authorization': '',
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
}
if (!options.header || !options.header['Content-Type']) {
options.header = head
}
if (whiteList.indexOf(options.url) === -1) {
if (!token) {
uni.showToast({
icon: "none",
title: "請先登錄"
})
uni.removeStorageSync("shopToken")
return Promise.reject("請先登錄")
} else {
options.header.Authorization = token
}
}
if (options.data) {
options.data['sign'] = encrypt.encryptMd5(options.data, encryptKey)
}
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + options.url,
method: options.method || 'GET',
data: options.data || {},
header: {
'Authorization': options.header.Authorization,
'Content-Type': options.header['Content-Type']
},
success: (res) => {
if (res.data.code !== 200) {
if (res.data.code === 1000 || res.datacode === 1001 || res.datacode ===
1002 || res.data.code === 1010 || res.data.code === 500) {
uni.showModal({
title: '提示',
content: '長時間未操作請重新登錄',
showCancel: false,
success: function(d) {
uni.removeStorageSync('shopToken')
uni.navigateTo({
url: '/pages/login/register',
})
}
});
} else if (res.data.msg != 'token不匹配') {
} else if (res.data.msg == 'token不匹配') {
res.data.msg = "登錄狀態(tài)過期請重新登錄"
}
uni.showToast({ icon: "none", title: res.data.msg })
reject(res.data.msg)
} else {
resolve(res.data)
}
},
fail(err) {
reject(err)
}
})
})
}第二步:訪問接口
settings.js
export const settings = {
// #ifdef MP-WEIXIN
BASE_URL: 'http://192.168.101.35', // 訪問接口
// #endif
// #ifdef H5
BASE_URL: '', // 訪問接口
// #endif
// BASE_URL: 'https://api.helicong.com:80', // 訪問接口
ENCRYPT_KEY: 'jdp*#(@KFJ322!@#$jkl(#jdlmkdhc', // 前端加密key
WHITE_LIST: ["/api/lifeMerchant/baseInfo/selectSortByDistance", "/api/middle/sendSms", "/api/lifeMerchant/account/merchantRegisterLogin"] , // 接口過濾白名單 ,'/alipay/credit','/alipay/pay',"/alipay/tradeRefund","/alipay/unFreeze"
}以上就是Uniapp如何封裝網(wǎng)絡(luò)請求方法demo的詳細內(nèi)容,更多關(guān)于Uniapp封裝網(wǎng)絡(luò)請求的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:
相關(guān)文章
JavaScript實現(xiàn)復制內(nèi)容到粘貼板代碼
最近做了一個前端項目,其中有需求:通過button直接把input或者textarea里的值復制到粘貼板里。下面小編給大家分享JavaScript實現(xiàn)復制內(nèi)容到粘貼板代碼,需要的朋友參考下2016-03-03
javaScript手機號碼校驗工具類PhoneUtils詳解
這篇文章主要為大家詳細介紹了javaScript手機號碼校驗工具類PhoneUtils,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12

