Diferència entre revisions de la pàgina «Exemple bàsic de funcionament de Webhooks. Servidor i client en node.js»

De things.cat
Salta a: navegació, cerca
m (Servidor de Webhooks en node.js)
m (Servidor de Webhooks en node.js)
Línia 14: Línia 14:
 
     res.sendStatus( 200 );
 
     res.sendStatus( 200 );
 
  } );
 
  } );
 
+
 
  app.listen( 9000, () => console.log( 'Node.js server started on port 9000.' ) );
 
  app.listen( 9000, () => console.log( 'Node.js server started on port 9000.' ) );
  

Revisió del 10:04, 17 set 2021

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

app.listen( 9000, () => console.log( 'Node.js server started on port 9000.' ) );

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://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