Exemple bàsic de funcionament de Webhooks. Servidor i client en node.js

De things.cat
La revisió el 10:02, 17 set 2021 per Jordi Binefa (discussió | contribucions) (Client de Webhooks en node.js)
Salta a: navegació, cerca

Servidor de Webhooks en node.js

En cas de no tenir el paquet express:

npm install express

Codi d'un servidor no segur de Webhooks en node.js:

// https://ckeditor.com/docs/cs/latest/examples/webhooks/webhooks-server-nodejs.html

const express = require( 'express' );
const app = express();
app.use( express.json() );

app.post( '/', ( req, res ) => {
   console.log( 'received webhook', req.body );
   res.sendStatus( 200 );
} );


Client de Webhooks en node.js

En cas de no tenir el paquet send-webhook:

npm install send-webhook

Codi d'un client de Webhooks en node.js que tramet a http://formacio.things.cat:9000 i http://iot.electronics.cat:9000/wh :

// sampleWebhookSender.js
// https://www.npmjs.com/package/send-webhook

const webhook = require('send-webhook');
 
const URLS = [
 //'http://example.com/webook_reciever',
 //'http://johndoe.com/webhook',
 //'http://incoming.com/recieve'
 'http://formacio.things.cat:9000',
 'http://iot.electronics.cat:9000/wh'
];

const payload = {
 // This can be anything you want to send.
 status: true,
 data: {
   message: 'This is a sample web-hook that will be sent via POST.'
 }
};

/* 
 You can also do it to a single URL by just putting in a string
 instead of an array.
*/


webhook(URLS, payload, (error, status) => {
 if(error) console.error(error);
 console.log('Webhooks have been sent.');
});



/*
   URL: http://johndoe.com/webhook
   TYPE: POST
   MIME: application/json
   DATA:
     {
       status: true,
       data: {
         message: 'This is a sample web-hook that will be sent via POST.'
       }
     }
*/

Funcionament