1. 请求封装及登录授权
import Vue from 'vue'
Vue.prototype.login = function(username, password) {
var _self = this;
uni.request({
url :`服务端地址(授权)`,
method:'POST',
header: {},
data : JSON.stringify({
code : res.code,
token : "login"
}),
success : function(res2){
if (res2.statusCode === 200) {
let token = 'Bearer ' + res2.data.access_token
uni.setStorageSync(_self.sessionKey,token);
} else {
uni.redirectTo({url:'/pages/authorize/authorize'});
return false;
}
}
})
}
Vue.prototype.sendRequest = function(param,backpage, backtype){
var _self = this,
url = param.url,
method = param.method,
header = {},
data = param.data || {},
token = "",
hideLoading = param.hideLoading || false;
var requestUrl = this.siteBaseUrl + url;
if(!data.token){
token = uni.getStorageSync(this.sessionKey);
if(!token){
_self.login(backpage, backtype);
return;
}else{
header.Authorization = token;
}
}
if(method){
method = method.toUpperCase();
if(method == "POST"){
header = {'content-type' : "application/x-www-form-urlencoded"};
header.Authorization = token
}else{
header = {'Accept' : "application/json"};
header.Authorization = token
}
}
if (!hideLoading) {
uni.showLoading({title:'加载中...'});
}
uni.request({
url: requestUrl,
method: method,
header: header,
data: data,
success: res => {
typeof param.success == "function" && param.success(res.data);
},
fail: (e) => {
console.log("网络请求fail:" + JSON.stringify(e));
uni.showModal({
content:"" + e.errMsg
});
typeof param.fail == "function" && param.fail(e.data);
},
complete: () => {
if (!hideLoading) {
uni.hideLoading();
}
typeof param.complete == "function" && param.complete();
return;
}
});
}
Vue.prototype.siteBaseUrl = '服务端地址(根目录)';
Vue.prototype.sessionKey = "myToken";
2. 登录授权页面
<script>
import login from '../../utils/request.js'
export default {
data() {
return {
username:'admin',
password:'123456',
};
},
onLoad() {
this.login(this.username,this.password);
}
}
</script>
3. 其他页面
<script>
export default {
data() {
return {
personInfo:{},
};
},
methods:{
getPersonInfo(){
this.sendRequest({
url : "服务端地址(根目录下地址)",
method : "GET",
data : {},
hideLoading : true,
success: (res) => {
if(res.code === 0){
this.personInfo = res.data.sysUser
}
}
})
}
},
beforeMount(){
this.getPersonInfo()
},
}
</script>