Uniapp如何封裝網(wǎng)絡請求方法demo
更新時間:2023年10月20日 11:58:35 作者:小拼拼
這篇文章主要為大家介紹了Uniapp如何封裝網(wǎng)絡請求方法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)絡請求方法demo的詳細內(nèi)容,更多關(guān)于Uniapp封裝網(wǎng)絡請求的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:
相關(guān)文章
JavaScript markdown 編輯器實現(xiàn)雙屏同步滾動
這篇文章主要介紹了JavaScript markdown 編輯器實現(xiàn)雙屏同步滾動,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08動態(tài)加載圖片路徑 保持JavaScript控件的相對獨立性
根據(jù)新界面的要求,需要一部分圖片來增強日期控件的美觀性??紤]到既要實現(xiàn)加載圖表的目標,又要保持控件的獨立性以便將來的移植。2010-09-09