1、request.js文件
const API_URL = "/api/";
const REQ_HEADERS = {
contentType: "Content-Type",
};
const CONTENT_TYPE = {
json: "application/json;",
form: "application/x-www-form-urlencoded;",
};
//请求loading
let ajaxTimes = 0;
const request = ({ url, method = "get", headers = {}, body = null } = {}) => {
ajaxTimes++;
uni.showLoading({
title: "加载中",
mask: true,
});
url = API_URL + url;
url.indexOf("?") === -1 ? (url += "?") : (url += "&");
url += "_t=" + new Date().getTime();
// post: [REQ_HEADERS.contentType]: CONTENT_TYPE.form,
return new Promise((resolve, reject) => {
uni.request({
url: url,
method: method,
data: body,
header: Object.assign(headers, {
Authorization: `Bearer ${uni.getStorageSync("token")}`,
[REQ_HEADERS.contentType]: CONTENT_TYPE.form,
}),
success: (res) => {
uni.hideLoading();
if (res.data.code === -1004) {
//根据code码判断是否需要重新登陆
uni.removeStorageSync("token");
uni.reLaunch({
url: "/pages/login/index",
});
return;
}
if (res.statusCode === 403 || res.statusCode === 502) {
uni.showToast({
icon: "none",
title: "系统错误!",
});
return;
}
if (res.data.code === 1) {
resolve(res.data);
return;
}
uni.showToast({
icon: "none",
title: res.data.msg,
});
},
fail: (err) => {
uni.showToast({
icon: "none",
title: "系统错误!",
});
reject(err);
},
//请求结束 成功失败都关闭loading
complete: () => {
ajaxTimes--;
if (ajaxTimes === 0) {
// 关闭正在等待的图标
uni.hideLoading();
}
},
});
});
};
export default request;
2、login-serice.js
import request from "@/utils/request";
// 验证码
export function loginCode(query) {
return request({
url: "code",
method: "POST",
body: query,
});
}
3、页面使用login.vue
<template>
</template>
<script>
import { loginCode} from '../../common/api/login-serice.js'
export default {
name: 'login',
data() {
return {
formData: {
username: '',
password: '',
}
}
},
methods: {
//获取验证码
async handleCodeImg() {
let codeData = await loginCode()
....
},
},
onReady() {
},
mounted() {
this.handleCodeImg()
},
}
</script>
<style lang="scss" scoped>
</style>