How to use JSON-RPC with NodeJS Express?

nodejs json

We’ll use Express to take JSON-RPC requests.

Install Express to take requests and jayson to process them:

$ npm install express body-parser jayson

Create a server.js:

const express = require('express')
const bodyParser = require('body-parser')
const jayson = require('jayson')

const cats = {
    speak: function(args, callback) {
        callback(null, 'meow')
    }
}
const dogs = {
    speak: function(args, callback) {
        callback(null, 'woof')
    }
}

const app = express()
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.post('/cats', jayson.server(cats).middleware())
app.post('/dogs', jayson.server(dogs).middleware())
app.listen(5000)

Start the server:

$ node server.js

Client

Use curl to send requests:

$ HDR='Content-type: application/json'
$ MSG='{"jsonrpc": "2.0", "method": "speak", "id": 1}'
$ curl -H $HDR -d $MSG http://localhost:5000/cats
{"jsonrpc":"2.0","result":"meow","id":1}
$ curl -H $HDR -d $MSG http://localhost:5000/dogs
{"jsonrpc":"2.0","result":"woof","id":1}

Updated 11 Sep 2018 thanks to Roman Frolov.