Every developer is familiar with http api and this demo quickly shows how we can create a classic client-server application using node-m2m.
Set your http resources as defined by the different paths along with the get and post methods.
You can customize your resources by defining your paths or routes with query strings and route parameters both in get and post methods.
$ npm install m2m
const { Device } = require('m2m');
let device = new Device(100);
device.connect(() => {
device.get('/update-data', (req, res) => {
console.log('req.query', req.query);
res.json(req.query);
});
device.post('/machine-control/:id/actuator/:number/action/:state', (req, res) => {
console.log('req.params', req.params);
console.log('req.body', req.body);
res.json({params:req.params, body:req.body});
});
device.post('/update-data', (req, res) => {
console.log('req.body', req.body);
res.send('device 100 data updated');
});
});
$ node device.js
$ npm install m2m
const { Device } = require('m2m');
let device = new Device(200);
device.connect(() => {
device.get('/device/state', (req, res) => {
res.json({id:100, state:'off'});
});
device.post('/update-data', (req, res) => {
console.log('req.body', req.body);
res.send('device 200 data updated');
});
device.post('/machine-control/:id/actuator/:number/action/:state', (req, res) => {
console.log('req.params', req.params);
console.log('req.body', req.body);
res.json({params:req.params, body:req.body});
});
});
$ node device.js
$ npm install m2m
const m2m = require('m2m');
let client = new m2m.Client();
client.connect(() => {
client.get({id:100, path:'/update-data?name=ed&status=member'}, (data) => {
console.log('device 100 get /update-data result', data);
});
client.get({id:200, path:'/device/state'}, (data) => {
console.log('device 200 device/state result', data);
});
client.post({id:100, path:'/update-data', body:{name:'Jim', age:'30'}}, (data) => {
console.log('device 100 post /update-data result', data);
});
client.post({id:200, path:'/machine-control/m120/actuator/25/action/on', body:{id:200, state:'true'}}, (data) => {
console.log('device 200 /machine-control result', data);
});
});
$ node client.js
You should get a result as shown below.
...
device 100 post /update-data result device 100 data updated
device 200 device/state result { id: 100, state: 'off' }
device 100 get /update-data result { name: 'ed', status: 'member' }
device 200 /machine-control result {
params: { id: 'm120', number: '25', state: 'on' },
body: { id: 200, state: 'true' }
}