1.0.5 • Published 11 months ago

@bucai/taro-request v1.0.5

Weekly downloads
1
License
ISC
Repository
github
Last release
11 months ago

taro-request

基于PromiseTarohttp请求,轻便,小巧,api友好,功能丰富

特别之处

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

使用方式

yarn add @bucai/taro-request npm install @bucai/taro-request --save import taroRequest from '@bucai/taro-request';

一步上手

首先来一个简单的get请求

// 向具有给定ID的用户发出请求
taroRequest.get('/user?id=12345')
.then(function (response) {
	console.log(response);
})
.catch(function (error) {
	console.log(error);
});

// 可选地,上面的请求也可以按照
taroRequest.get('/user', {
	params: {
			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 taroRequest.get('/user?ID=12345');
		console.log(response);
	} catch (error) {
		console.error(error);
	}
}

多种方法使用async/waait,开启代码便捷、畅快之旅

接着再来一个post请求

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

执行多并发请求例子

function getUserAccount() {
  return taroRequest.get('/user/12345');
}

function getUserPermissions() {
  return taroRequest.get('/user/12345/permissions');
}

taroRequest.all([getUserAccount(), getUserPermissions()])
	.then(response =>{
			// dosoming ...
	});

请求方法别名

当然除了常见的get,post其他的请求也统一封装

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

note: 当使用别名方法url时,methoddata属性不需要在config中指定。

全局配置

使用场景用户请求需要token,或者地址前缀,一次配置,省时省心。

taroRequest.defaults.baseURL = 'https://api.example.com';
taroRequest.defaults.headers['Authorization'] = AUTH_TOKEN;
taroRequest.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

致谢 && 参考

License

MIT

1.0.5

11 months ago

1.0.4

11 months ago

1.0.3

3 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago