【uniapp的request封装和提示的封装】

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
    });
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值