uni-app request请求

request

export default (url, method, params, formStatus, headers) => {
    let token =  uni.getStorageSync("userToken")
    if (!headers) {
        headers = {
            "Content-Type": "application/json; charset=utf-8",
            'x-ajax': 'json',
            'CLIENT-TOC': 'Y',
            'x-requested-with': 'XMLHttpRequest',
            'Authorization': `${token}`,
        }
    }
    return new Promise((resolve, reject) => {
        uni.request({
            url: `/api` + url,
            method: method,
            data: params,
            header: headers,
            success: function (res) {
                let data = res.data;
                // token过期,跳转登录页面
                if (data.code == 403 || data.code == 424) {
                    setTimeout(() => {
                        uni.reLaunch({
                           url: `/pages/login/login`
                        })
                    }, 1500)
                }
                // 请求接口返回错误提示
                if (data.code == 1) {
                    uni.showToast({
                        title: data.msg,
                        icon: 'none'
                    })
                }
                // 是否需要显示提示
                if (formStatus) {
                    uni.$u.toast(data.msg);
                }
                resolve(data);
            },
            fail(err) {
                reject(err);
            },
        });
    });
};

api集中管理

import request from "./request";

const newApi = {
    // 优惠券列表
    async getCouponsPage(data) {
        return await request(`/admin/bsmsActivityCoupon/claimCakeCoupons`, 'GET', data, false)
    },
    // 需要自定义请求头
    async getAuthToken(data) {
        return await request(`/admin/oauth2/token?`, 'POST', data, false, {
            'Authorization': 'Basic c3RvcmU6c3RvcmU=',
            'Content-type': 'application/x-www-form-urlencoded',
            'isToken': false,
            'CLIENT-TOC': 'Y'
        })
    },
export default newApi

调用

import newApi from "@/api/newApi"
newApi.getCouponsPage()

你可能感兴趣的:(Uni-app,uni-app)