1,寫一個(gè)公共的api.js
let baseURL = 'http://443548ef.cpolar.cn/';//公共api地址。示范
export const myRequest = (options) => {
return new Promise((resolve, reject) => {
uni.request({
url: baseURL + options.url, //接口地址:前綴+方法中傳入的地址
method: options.method || 'GET', //請(qǐng)求方法:傳入的方法或者默認(rèn)是“GET”
data: options.data || {}, //傳遞參數(shù):傳入的參數(shù)或者默認(rèn)傳遞空集合
dataType:options.dataType || "json",
header: {
'Admin-Token':uni.getStorageSync('Admin-Token'), //自定義請(qǐng)求頭信息
'visa':uni.getStorageSync('userId'), //自定義請(qǐng)求頭信息
'content-type':options.headers['Content-Type'] || 'application/x-www-form-urlencoded;charset=UTF-8'
},
success: (res) => {
if(res.data.code == 302){//用戶另一端登錄
uni.showModal({
title: '提示',
content: res.data.msg,
showCancel: false,
success: function (res) {
if (res.confirm) {
uni.reLaunch({
url: '/pages/login/login'
});
}
}
});
}else if(res.data.code == 500){
uni.showToast({
title: res.data.msg,
icon: 'none',
mask: true,
duration: 2000
});
}else{
uni.showToast({
title: res.data.code,
icon: 'none',
mask: true,
duration: 2000
});
resolve(res.data);
}
//返回的數(shù)據(jù)(不固定,看后端接口,這里是做了一個(gè)判斷,如果不為true,用uni.showToast方法提示獲取數(shù)據(jù)失敗)
// if (res.data.success != true) {
// return uni.showToast({
// title: '獲取數(shù)據(jù)失敗',
// icon: 'none'
// })
// }
// 如果不滿足上述判斷就輸出數(shù)據(jù)
},
// 這里的接口請(qǐng)求,如果出現(xiàn)問題就輸出接口請(qǐng)求失敗
fail: (err) => {
console.log( baseURL + options.url)
console.log(err)
reject(err)
}
})
})
}
2,接下來一些請(qǐng)求方法封裝,以登錄為例。login.js
import {myRequest} from 'api.js'
//登錄
export function login(username, password) {
return myRequest({
url: 'login',
method: 'post',
data: {
username,
password
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
})
}
3,login.vue 點(diǎn)擊發(fā)送請(qǐng)求
import {login} from '@/api/login.js';
loginHandle(){
login(this.username,this.password).then(res => {
const code = res.code;
if (code == 0) {
uni.showToast({
title: '登錄成功'
})
setTimeout(() => {
uni.redirectTo({
url: '/pages/index/index',
})
}, 500)
} else {
uni.showToast({
title:res.msg,
icon: 'none',
mask: true,
duration: 2000
})
}
}).catch(err => {
console.log(err)
})
},
文章來源地址http://www.zghlxwxcb.cn/news/detail-660925.html
文章來源:http://www.zghlxwxcb.cn/news/detail-660925.html
到了這里,關(guān)于uniapp api請(qǐng)求接口 封裝的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!