User Tools

Site Tools


Differences

This shows you the differences between two versions of the page.

Link to this comparison view

js:jeyson [2018-11-13 16:06]
ziggi
js:jeyson [2020-02-15 00:57]
Line 1: Line 1:
- 
-=====Jeyson JSON RPC usage sample===== 
- 
-In the sample I used named parameters. 
- 
-NPM: https://​www.npmjs.com/​package/​jayson 
- 
-===Server code=== 
- 
-<code javascript jserver.js>​ 
-const express = require('​express'​) 
-const bodyParser = require('​body-parser'​) 
-const jayson = require('​jayson'​) 
- 
-const rpcBundle = { 
-    add: function(a, b, callback) { 
-        console.log({a,​ b}) 
-        let c = a + b; 
-        callback(null,​ c); 
-    } 
-} 
- 
-const app = express() 
-app.use(bodyParser.urlencoded({extended:​ true})) 
-app.use(bodyParser.json()) 
- 
-app.post('/​api',​ jayson.server(rpcBundle,​ { collect: false }).middleware()) 
- 
-app.listen(80) 
-</​code>​ 
- 
-===Client code=== 
- 
-<code javascript jclient.js>​ 
-var jayson = require('​jayson'​);​ 
- 
-var client = jayson.client.http('​http://​localhost:​80/​api'​);​ 
- 
-var functionName = '​add';​ 
-var functionParams = {a: 1, b: 2} 
-client.request(functionName,​ frunctionParams,​ function(err,​ response) { 
-    if (err) throw err; 
-    console.log(response.result);​ 
-}); 
-</​code>​ 
- 
-===Output=== 
-<​file>​ 
-$ node jclient.js ​ 
-{ result: 3 } 
-</​file>​ 
- 
-===Dump of request and response=== 
- 
-<​code>​ 
-POST /api HTTP/1.1 
-Content-Length:​ 99 
-Content-Type:​ application/​json;​ charset=utf-8 
-Accept: application/​json 
-Host: localhost 
-Connection: close 
- 
-{ 
-   "​method":"​add",​ 
-   "​jsonrpc":"​2.0",​ 
-   "​params":​{"​a":​1,"​b":​2},​ 
-   "​id":"​933587cc-6669-4957-96e3-8af17d457c43"​ 
-} 
-</​code>​ 
- 
-<code > 
-HTTP/1.1 200 OK 
-X-Powered-By:​ Express 
-Content-Length:​ 72 
-Content-Type:​ application/​json;​ charset=utf-8 
-  
-{ 
-  "​jsonrpc":"​2.0",​ 
-   "​id":"​933587cc-6669-4957-96e3-8af17d457c43",​ 
-   "​result":​3 
-} 
-</​code>​ 
- 
----- 
-[<>]