a jsonrpc client for node/browser/react native
超轻量级的 json-rpc 2.0 协议实现,基于新的标准 fetch api 来实现,另外为了方便使用集成了另外一个库 frisbee,实现了常见的 http 操作
-
安装依赖项
npm install zhangxhbeta/xhjsonapi --save ``` 2. 然后获取 XHJsonApi 对象
```bash
import XHJsonApi from 'xhjsonapi'; ``` 3. 查看例子开始使用
与 react native 环境基本类似,区别在于 Node 环境缺少 fetch 和 es6-promise,需要安装
-
安装依赖项
npm install es6-promise --save npm install isomorphic-fetch --save npm install zhangxhbeta/xhjsonapi --save ``` 2. 然后获取 XHJsonApi 对象
```bash
import 'isomorphic-fetch';
import es6promise from 'es6-promise'; es6promise.polyfill();
import XHJsonApi from 'xhjsonapi'; ``` 3. 查看例子开始使用
<!doctype html>
<title></title> <!-- 解决 ie8 下面 es5 的问题 -->
<!--[if lt IE 9]>
<script src="scripts/es5-shim.js"></script>
<![endif]-->
<!-- 引入 promise 库` -->
<script src="scripts/es6-promise.js"></script>
<!-- 引入 fetch 库 -->
<script src="scripts/fetch.js"></script>
<!-- 引入 frisbee -->
<script src="scripts/frisbee.js"></script>
<!-- 引入 xhjsonapi -->
<script src="scripts/xhjsonapi.js"></script>
</head>
<body>
</body>
methods 是一个服务端暴漏的方法列表,提供这个列表后会将这些方法按照模块都生成出来,客户端就可以直接调用这些方法
// 初始化 api(仅设置一次即可)
var api = new XHJsonApi({
baseURI: 'localhost:8080/app',
rpcPath: 'json-rpc',
methods: [
{
name: 'news',
remoteName: 'newsInterface',
methods: ['getHotNews', 'getLatestNews']
},
{
name: 'otherModule',
methods: ['foo', 'bar']
}
],
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
// 在需要用的地方调用 api
// 将发送报文 {"jsonrpc":"2.0","method":"newsInterface.getHotNews","id":1,"params":[]}
api.news.getHotNews().then(result) {
console.log(result);
}.catch(e) {
console.log(e);
}
// 如果需要传参数可以这样
// 将发送报文 {"jsonrpc":"2.0","method":"otherModule.foo","id":1,"params":["the","best",1]}
api.otherModule.foo('the', 'best', 1).then(result) {
console.log(result);
}.catch(e) {
console.log(e);
}
- List of available HTTP methods:
api.get(path, options, callback)
- GETapi.head(path, options, callback)
- HEAD (现在暂时不能用)api.post(path, options, callback)
- POSTapi.put(path, options, callback)
- PUTapi.del(path, options, callback)
- DELETEapi.options(path, options, callback)
- OPTIONS (现在暂时不能用)api.patch(path, options, callback)
- PATCH
具体用法,参见 frisbee 的文档