在根目录创建utils文件
utils下创建一个request.js
request.js代码如下:
const baseUrl = '接口地址';
// 带 Token 请求
const request = (opts, data) => {
uni.onNetworkStatusChange(function(res) {
if (!res.isConnected) {
uni.showToast({
title: '网络连接不可用!',
icon: 'none'
});
}
return false
});
let token = uni.getStorageSync('token');
let httpDefaultOpts = {
url: baseUrl + opts.url,
data: opts.data,
method: opts.method || 'GET',
header: opts.method == 'get' ? {
'token': token,
'X-Requested-With': 'XMLHttpRequest',
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
} : {
'token': token,
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json; charset=UTF-8'
},
dataType: 'json',
}
console.log('接口=',httpDefaultOpts);
let promise = new Promise(function(resolve, reject) {
uni.request(httpDefaultOpts).then(
(res) => {
console.log(res)
if (res.data.code == 200) {
resolve(res)
} else {
if (res.data.code == 401) {
uni.showModal({
title: '提示',
content: res.data.message,
success: function (res) {
if (res.confirm) {
uni.reLaunch({
url: '/pages/index/index'
});
uni.clearStorageSync();
}
}
});
uni.reLaunch({
url: '/pages/index/index'
});
uni.clearStorageSync();
} else {
resolve(res)
uni.showToast({
title: '' + res.data.message,
icon: 'none'
})
}
}
}
).catch(
(response) => {
reject(response)
}
)
})
return promise
};
// 导出去
export default request;
根目录创建api文件
// /引入request.js文件
import request from "../../utils/request.js";
/* 登录 */
export function login(data) {
return request({
url: "/login",
method: "post",
data
});
}
/* 获取验证码 */
export function captchaImage() {
return request({
url: '/captchaImage',
method: 'get'
})
}
页面使用如下:
<script>
import {
login,
captchaImage
} from "@/api/login/index.js"
export default {
data() {
return {
img: '',
params: {
username: '',
password: '',
uuid: '',
code: ''
}
}
},
onShow() {
this.getCaptchaImage()
},
methods: {
/* 获取验证码 */
async getCaptchaImage() {
const res = await captchaImage()
},
/* 立即登录 */
async goLogin() {
const res = await login()
}
}
}
</script>