Exemple bàsic de funcionament de Webhooks. Servidor i client en node.js
La revisió el 10:29, 17 set 2021 per Jordi Binefa (discussió | contribucions)
Contingut
Introducció
Què són els Webhooks i com funcionen
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
Ordre al terminal de cada servidor que ha d'escoltar webhooks:
node webhookserver.js
Resposta al terminal del servidor:
Node.js server started on port 9000.
Ordre al terminal del client que tramet webhooks:
node sampleWebhookSender.js
Resposta al terminal del client:
Webhooks have been sent.
Resposta a cada terminal de cada servidor:
Node.js server started on port 9000. received webhook { status: true, data: { message: 'This is a sample web-hook that will be sent via POST.' } }