domenica 28 ottobre 2018

Creare un WebService con node.js


Per prima cosa creiamo il WSDL del servizio aiutandoci con l'editor contenuto in Eclipse Java EE Developer
Procedere nel seguente modo

File -> New -> Web Services -> WSDL File

Name = MyGreatService
prefix = tns
Target namespace = http://www.example.org/MyGreatService

--> Add Service
Name = MyGreatService
Port name = Calculus
Protocol = SOAP
Port address = http://localhost:8000/MyEndpoint

--> Add Port Type
Name = Calculus
Operation name = Add
(parameters Add) ---> intA int, intB int
(parameters AddResponse) --> out int

--> Add Binding
Name = CalculusSoap
... Generate Binding Content:
Port type = tns:Calculus
Protocol = SOAP

...--> MyGreatService
... Set Binding --> Existing Binding = CalculusSoap


Salvare il file wsdl con il nome CalculusService.wsdl

Per node.js ci appogeremo alla libreria https://github.com/vpulim/node-soap

Andiamo a creare il server e salviamolo col nome MyServer.js
var myService = {
MyGreatService: {
Calculus: {
Add: function(args) {
return {
out: (args.intA + args.intB)
}
},
}
}
  };
   
  var soap = require('soap');
  var http = require('http');
  
  var xml = require('fs').readFileSync('./CalculusService.wsdl', 'utf8');
  var server = http.createServer(function(request, response) {
      response.end('404: Not Found: ' + request.url);
  });

  server.listen(8000, function() {
  soap.listen(server, '/MyEndpoint', myService, xml);
  });


Adesso creiamo il client e salviamo con nome Client.js
  var soap = require('soap');
  var url = 'http://localhost:8000/MyEndpoint?wsdl';
  
  var args = {intA: 2, intB: 33};
  
soap.createClient(url, function(err, client) {
client.Add(args, function(err, result) {
if (err) {
console.log("Errore ", err.body);
} else {
console.log(result);
}
});
});


Eseguire il server in una finestra e poi il client in un'altra.


;-)

Nessun commento: