User Tools

Site Tools


This is an old revision of the document!


Jeyson JSON RPC usage sample

In the sample I used named parameters.

NPM: https://www.npmjs.com/package/jayson

Server code

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)

Client code

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);
});

Output

$ node jclient.js 
{ result: 3 }

Dump of request and response

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"
}
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
}

First PagePrevious PageBack to overviewNext PageLast Page