美文网首页js css html
uni-app中调取接口的三种方式,以及请求封装

uni-app中调取接口的三种方式,以及请求封装

作者: 扶得一人醉如苏沐晨 | 来源:发表于2022-10-10 10:32 被阅读0次

    一、uni-app中调取接口的三种方式

    1、uni.request({})

    uni.request({

    url:'/api/getIndexCarousel.jsp',

    method:'get',

    success:res=>{

    console.log(res.data);

    this.carouselData = res.data

    }

    })

    2、uni.request({}).then()

    uni.request({

    url:'/api/getIndexCarousel.jsp',

    method:'get',

    }).then((result)=>{

    let [error,res] = result;

    //result将返回一个数组[error,{NativeData}]

    //NativeData:调取接口后返回的原生数据

    if(res.statusCode === 200){

    this.carouselData = res.data

    }

    if(res.statusCode === 404){

    console.log('请求的接口没有找到');

    }

    })

    3、async/await

    async:用在函数定义的前面

    async request(){ //函数体;}

    await:用在标明了async关键字的函数内部,异步操作的前面。

    onLoad() {

    this.request();

    },

    methods: {

    async request(){

    let result = await uni.request({

    url:'/api/getIndexCarousel.jsp'

    })

    console.log(result)

    let [err,res] = result;

    if(res.statusCode === 200){

    this.carouselData = res.data;

    }

    }

    }

    二、封装uni.request();

    import {

    baseUrl

    } from "../config/env.js"

    console.log(baseUrl)

    import {

    getStore

    } from "@/util/store";

    import errorCode from "@/const/errorCode";

    let request = (params) => {

    // 请求参数

    var url = baseUrl + param.url,

    method = param.method,

    header = {},

    data = param.data || {},

    hideLoading = param.hideLoading || false;

    const isToken = (params.headers || {}).isToken === false;

    const TENANT_ID = getStore({

    name: "tenantId"

    });

    const token = getStore({

    name: "access_token"

    });

    if (token && !isToken) {

    params.headers["Authorization"] = "Bearer " + token; // token

    }

    if (TENANT_ID) {

    params.headers["TENANT-ID"] = TENANT_ID; // 租户ID

    }

    if (method) {

    method = method.toUpperCase(); //小写改为大写

    if (method == "POST") {

    // uni.request 默认是application/json

    header = {

    'content-type': "application/x-www-form-urlencoded"

    };

    } else {

    header = {

    'content-type': "application/json"

    };

    }

    }

    //加载圈

    if (!hideLoading) {

    uni.showLoading({

    title: '加载中...'

    });

    }

    return new Promise((resolve, reject) => {

    uni.request({

    url: url,

    data: data,

    method: method,

    header: header,

    success: (res) => {

    const status = Number(res.statusCode) || 200;

    const message = res.data.msg || errorCode[status] || errorCode["default"];

    // 后台定义 424 针对令牌过去的特殊响应码

    if (status === 424) {

    uni.showModal({

    title: "系统提示",

    content: "令牌状态已过期,请点击重新登录",

    showCancel: false,

    success: (res) => {

    if (res.confirm) {

    console.log('用户点击确定');

    }

    }

    });

    return;

    }

    if (status !== 200 || res.data.code === 1) {

    uni.showToast({

    title: message,

    icon: 'none'

    })

    reject(new Error(message));

    }

    resolve(res)

    },

    fail: (error) => {

    // 处理 503 网络异常

    // if (error.response.status === 503) {

    // Message({

    // message: error.response.data.msg,

    // type: "error",

    // });

    // }

    reject(new Error(error));

    },

    complete: () => {

    if (!hideLoading) {

    uni.hideToast()

    }

    }

    })

    })

    }

    相关文章

      网友评论

        本文标题:uni-app中调取接口的三种方式,以及请求封装

        本文链接:https://www.haomeiwen.com/subject/ducoartx.html