zoukankan      html  css  js  c++  java
  • 基于Promise封装uni-app的request方法,实现类似axio

    uni-request

    基于Promise封装uni-app的request方法,h5和小程序均可使用

    特别之处

    • 支持Promise API
    • 拦截请求和响应
    • 转换请求和响应数据
    • 取消请求
    • 自动转换为JSON数据
    • 超时请求
    • 告别callback
    • 支持默认请求前缀
    • 支持并发请求

    使用方式

    uni-app框架中

    安装(项目根目录下运行)

    npm install uni-request --save
    

    文件中引用

    import uniRequest from 'uni-request';

    使用方法

    请求方法的别名

    uniRequest.request(config)
    uniRequest.get(url[, config])
    uniRequest.delete(url[, config])
    uniRequest.head(url[, config])
    uniRequest.options(url[, config])
    uniRequest.post(url[, data[, config]])
    uniRequest.put(url[, data[, config]])
    uniRequest.patch(url[, data[, config]])
    

    全局配置

    uniRequest.defaults.baseURL = 'https://yourapi.domain.com';
    uniRequest.defaults.headers.common['Authorization'] = AUTH_TOKEN;
    uniRequest.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    

    发送get请求

    // 向具有给定ID的用户发出请求
    uniRequest.get('/user?id=12345')
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
    
    // 可选地,上面的请求也可以按照
    uniRequest.get('/user', {
        data: {
            id: 'number'
        }
    }).then(function (response) {
        console.log(response);
    }).catch(function (error) {
        console.log(error);
    });
    
    // 想要使用 async/await? 将`async`关键字添加到外部函数/method
    async function getUser() {
        try {
            const response = await uniRequest.get('/user?ID=12345');
            console.log(response);
        } catch (error) {
            console.error(error);
        }
    }
    

    发送post请求

    uniRequest.post('/user', {   
            firstname : 'firstname',
            lastname : 'lastname'    
    }).then(function (response) {
        console.log(response);
    }).catch(function (error) {
        console.log(error);
    });
    

    以上就是基本用法,如果掌握了就可以使用了uni-request,下面是一份完整的代码示例包含了在uni-app中使用uni-request和vuex的详细用法,有问题可以评论区留言,会及时回复

  • 相关阅读:
    在yii中使用Filter实现RBAC权限自动判断
    关于WEB设计透明和阴影
    一句话扯扯数据结构的概念点
    Console API Google 浏览器开发人员工具使用
    git提交项目时候,忽略一些文件
    学习笔记 如何解决IE6 position:fixed固定定位问题{转载}
    [转载]yii jquery折叠、弹对话框、拖拽、滑动条、ol和ul列表、局部内容切换
    Jquery 常用方法经典总结【砖】
    PHP中冒号、endif、endwhile、endfor这些都是什么
    [转载]救命的PHP代码
  • 原文地址:https://www.cnblogs.com/ydam/p/10983531.html
Copyright © 2011-2022 走看看