基于Promise封装uni-app的request方法,实现类似axios形式的请求

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

转载于:https://my.oschina.net/u/2428630/blog/3004860

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值