uni-app请求方法的封装

export const baseUrl = 'http://xxx.xx.xxx:8080'
// 获取Token
function getToken() {
    try {
        const token = uni.getStorageSync('token');
        if (token) {
            return token
        } else {
            return ''
        }
    } catch (e) {
        console.log(e)
    }
}

// 获取请求头
function getHeaders() {
    let token = getToken()
    let header = {
        "token": token,
        "Content-Type": "application/json", //根据自己的数据类型
        // "Content-Type":"application/x-www-form-urlencoded",
    }
    return header
}

let request = function(data) {
    data.method = data.method.toUpperCase()
    if (!['GET', 'POST'].includes(data.method)) {
        uni.showToast({
            title: `暂不支持的请求方式: ${data.method}`,
            icon: 'none'
        });
        return
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + data.url,
            method: data.method,
            data: data.params,
            header: getHeaders(),
        }).then(res => {
            switch (res[1].statusCode) {
                case 200:
                    resolve(res[1])
                    break
                default:
                    reject(res)
            }
        }).catch(
            (response) => {
                reject(response)
            }
        )
    })
}

export default  request;

import request from '../../common/js/util/request'

export function getPageSet() {
    return request({
        url: '/system/xxxx',
        method: 'post',
    })
}


你可能感兴趣的:(uni-app请求方法的封装)