request.js文件
// requewt.js
const baseUrl = 'http://59.110.166.212:8006/api';
// 获取token
function getToken() {
const storageData = uni.getStorageSync('token');
if (storageData) {
const { token } = JSON.parse(storageData);
return token; // 返回 token
}
return ''; // 如果没有找到数据,返回 null 或其他合适的值
}
export const request = (options) => {
return new Promise((resolve, reject) => {
// 设置请求头
const header = {
'content-type': options.isJson ? 'application/json' : 'application/x-www-form-urlencoded',
token: getToken()
// ...options.header // 可以传入额外的请求头参数
};
uni.showLoading({
title: '加载中',
mask: true
});
uni.request({
url: baseUrl + options.url, //接口地址:前缀+方法中传入的地址
method: options.method || 'POST', //请求方法:传入的方法或者默认是“POST”
data: options.data || {}, //传递参数:传入的参数或者默认传递空集合
header: header, //接收请求的header
success: (res) => {
uni.hideLoading();
if (res.data.retCode == '601') {
uni.reLaunch({
url: '/pages/login/login'
});
return uni.$u.toast('登录过期,请重新登录');
}
resolve(res.data, '成功');
},
// 这里的接口请求,如果出现问题就输出接口请求失败
fail: (err) => {
uni.hideLoading();
reject(err);
}
});
});
};
api目录里接口的方法
import { request } from '@/utils/request.js';
//登录 post请求
export const loginIndex = (data) => {
return request({
url: '/user/login',
isJson: true,
data: data
});
};
最后在vue文件里调用
<template>
<view>
<button @click="logins">账号密码登录</button>
</view>
</template>
<script setup>
import { loginIndex } from '@/api/index.js';
import { utils } from '@/utils/utils.js';
const logins = async () => {
const account = 'admin';
const password = '123456';
// 通常登录请求需要一个包含用户名和密码的对象
const credentials = { account: account, password: password };
const res = await loginIndex(credentials);
console.log(res);
};
</script>
<style>
/* 添加您的样式 */
</style>
在utils里封装轻提示
export const utils = (title = '数据加载失败!', icon = 'none') => {
uni.showToast({
title,
icon,
mask: true
});
};