sx-fetch
基于axios的前端网络请求库。
安装
npm:
$ npm install sx-fetch --save
yarn:
$ yarn add sx-fetch
使用
初始化:
; fetch;
sx-fetch
0.2.1 版本及以上支持以下写法。
fetch;
初始化时如果需要配置 interceptors
,仍需使用 setOptions
方法。
instance.interceptors
请参考 axios#interceptors 用法。
默认处理方法如下:
instanceinterceptorsrequest; instanceinterceptorsresponse;
发送请求:
fetch;
创建新的fetch实例
需要
sx-fetch
版本 >= 0.2.1
应用中有时需要同时使用不同的fetch配置,例如需要请求多个服务器。这时可以使用 create
方法创建新的fetch实例。
fetch.create([options])
const instance = fetch;
新创建的fetch实例 instance
的行为与默认的fetch实例完全相同,你可以使用 init
方法初始化该实例.
还可以在创建实例的同时传入配置参数。
instance
还可以在创建实例的同时传入配置参数。
const instance = fetch;
defaults
属性设置fetch实例的配置信息
通过 需要
sx-fetch
版本 >= 0.2.1
fetchdefaultsbaseURL = 'http://localhost:8080';fetchdefaultstimeout = 10000;fetchdefaultsheaderscommon'auth_token' = AUTH_TOKEN;
可以给指定实例设置配置信息
const instance = fetch; instancedefaultsbaseURL = 'http://localhost:8080';...
mock请求使用 mockDefaults
属性来配置。
fetchmockDefaultsbaseURL = 'http://localhost:8080';...
sx-fetch API
请求方法
fetch.get(url[, params[, options]])
fetch.post(url[, params[, options]])
fetch.del(url[, params[, options]])
fetch.put(url[, params[, options]])
fetch.patch(url[, params[, options]])
fetch.singleGet(url[, params[, options]])
Param | Description | Type | Default |
---|---|---|---|
[url] | 接口地址 | String |
/ |
[params] | 请求参数对象(get 请求参数会自定追加到url后。) |
Object |
{} |
[options] | 配置参数 | Object |
{} |
[options.errorTip] | 请求失败的提示信息 | String | Boolean |
get: '获取数据失败!'、 post: '操作失败!' |
[options.successTip] | 请求成功的提示信息 | String | Boolean |
false |
[options.timeout] | 请求超时时间(ms) | Number |
10000 |
options
详细配置参数参考 axios#request-config;
并发请求
需要
sx-fetch
版本 >= 0.2.1
同时发起多个请求,全部请求完成之后再执行回调。
可以使用 Promise.all()
方法,sx-fetch
也内置了 all
方法。
fetch.all(iterable)
const getUser = fetch;const getList = fetch; fetchallgetUser getList;
react 组件装饰器
使用装饰器方法 inject
将fetch注入到react组件的props中。当组件销毁时,未完成的请求会被中断。
注意:注入到react组件内的fetch实例只包含网络请求的方法,不包含其他方法及属性。
@fetch.inject([options])
Param | Description | Type | Default |
---|---|---|---|
[options] | Object |
{} | |
[options.propName] | 注入props的属性名 | String |
$fetch |
;; @fetch { const $fetch = thisprops; $fetch; } ...
注入多个fetch实例必须传入 propName
,否则props中的fetch实例会被覆盖。
const instance = fetch; @fetch@instance { const $fetch = thisprops; $fetch; $instance; } ...