今天分享一下uniapp項目的網(wǎng)絡(luò)請求如何封裝,不知道大家開發(fā)微信小程序項目是用什么開發(fā)工具,我個人更喜歡用uniapp,無論是從項目擴(kuò)展方向還是開發(fā)效率來說,uniapp都是首選。
1:創(chuàng)建一個項目工具庫,http.js
//提示
hint(title, duration, mask, icon) {
uni.showToast({
title: title,
duration: duration ? duration : 2000,
mask: mask,
icon: icon == 'success' ? 'success' : icon == 'error' ? 'error' : icon == 'fail' ? 'fail' :
icon == 'exception' ? 'exception' : icon == 'loading' ? 'loading' : 'none',
});
},
//加載彈框
loading(title, mask) {
uni.showLoading({
title: title,
mask: mask
});
},
//隱藏加載彈框
hideLoading() {
uni.hideLoading();
},
//模擬彈窗
modal(content, showCancel, confirm, cancel, cancelText) {
uni.showModal({
title: '提示',
content: content,
showCancel: !showCancel,
cancelText: cancelText ? cancelText : '取消',
success: function(res) {
if (res.confirm) {
confirm()
} else if (res.cancel) {
cancel()
}
}
});
},
//因為開發(fā)時是在瀏覽器開發(fā),涉及到跨域,所以要做條件判斷,瀏覽器做跨域處理,手機(jī)直接使用地址
reqAddress() {
// #ifdef H5
return "/api"
// #endif
// #ifndef H5
return "http://xxxxx"http://替換成自己的地址
// #endif
},
// 設(shè)置token
setToken(data) {
uni.setStorageSync('token', data)
},
// 獲取token
getToken() {
return uni.getStorageSync('token')
},
//數(shù)據(jù)請求
request(url, method, data, Loading, isToken,isData, isForm ) {
if (!Loading) {
http.loading('加載中', true)
}
return new Promise((resolve, reject) => {
uni.request({
url: http.reqAddress() + url,
data: data,
method: method,
header: {
'content-type': isForm ? 'application/x-www-form-urlencoded' :
'application/json',
'Authorization': isToken ? '' :http.getToken(),
},
dataType: 'json',
success(res) {
if (!Loading) {
http.hideLoading()
}
if(isData){
resolve(res)
}else{
if (res.data.code == 200) {
resolve(res.data)
} else if (res.data.code == 401) {
http.hint("請重新登錄")
uni.reLaunch({
url: '/pages/login/login-phone/login-phone'
})
} else if (res.data.code == 500) {
resolve(res.data)
http.hint(res.data.msg)
} else {
resolve()
}
}
},
fail(rej) {
if (!Loading) {
http.hideLoading()
}
http.hint("網(wǎng)絡(luò)不給力,請稍后再試~")
reject(rej)
}
})
})
}
}
export default http
在vite.config.js文件中配置跨域文章來源:http://www.zghlxwxcb.cn/news/detail-735042.html
server: {
port: 3000,
proxy: {
'/api': {
target:'http:xxxxxx',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, ''),
}
}
}
這樣,一個全局網(wǎng)絡(luò)請求工具就完成了,含有content-type字段判斷,200,401,500狀態(tài)碼提示信息等功能,微信小程序的話只需要用hbuilder工具編譯到微信小程序即可,謝謝觀看,歡迎指正!文章來源地址http://www.zghlxwxcb.cn/news/detail-735042.html
到了這里,關(guān)于uniapp及微信小程序封裝全局網(wǎng)絡(luò)請求,彈框和hint提示的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!