commons目錄下加 request.js
// 引入配置文件
import config from "./config.js";
import User from "./user.js";
export default{
config:{
baseUrl:config.webUrl,
header:{
'Content-Type':'application/json;charset=UTF-8',
'Content-Type':'application/x-www-form-urlencoded',
'Authorization':uni.getStorageSync('token'),
},
data: {},
method: "GET",
dataType: "json",
withCredentials: true
},
request(options = {}){
// options.header ||
options.header = this.config.header;
options.method = options.method || this.config.method;
options.dataType = options.dataType || this.config.dataType;
options.url = this.config.baseUrl+options.url;
// TODO:token增加等操作
if (options.Authorization) {
// 驗證用戶是否登錄
if (!this.checkToken(options.checkToken)) return;
// 驗證用戶操作權限(驗證是否綁定手機號碼)
if (!this.checkAuth(options.checkAuth)) return;
options.header.Authorization = User.token;
}
return uni.request(options);
},
// get 方法
get(url,data,options={}){
options.url = url;
options.data = data;
options.method = 'GET';
return this.request(options);
},
// post 方法
post(url,data,options={}){
this.config.header.Authorization = uni.getStorageSync('token');
options.url = url;
options.data = data;
options.method = 'POST';
return this.request(options);
},
// 錯誤處理
errorCheck(err,res,errfun = false,resfun = false){
console.log(err)
if (err) {
typeof errfun === 'function' && errfun();
uni.showToast({ title: 'fail to load',icon:"none" });
return false;
}
if (res.data.code) {
typeof errfun === 'function' && resfun();
uni.showToast({ title: res.data.errorMessage,icon:"none" });
return false;
}
return true;
},
}
main.js
import request from "./commons/request.js";
Vue.prototype.$http = request;
引入示例
async register(data) {
let [err, res] = await this.$http.post('/userCt/login', {
//請求賬號密碼登錄接口
password: this.password,
userName: this.mobile
});
// 這裏是錯誤的回調,如果請求的接口錯誤,或者需要自定義返回的日誌,可以在這裏處理
if (!this.$http.errorCheck(err, res)) return;
if (res.data.code == 0) {
//這裏這裏是成功的回調
}
}