Node.js: how to send a request to a web service in SOAP

Node.js: how to send a request to a web service in SOAP

To send a request to a web service in SOAP with Node.js, you need to follow some basic steps.

To send a request to a web service in SOAP with Node.js, you need to follow some basic steps.

First, you need to install the soap npm module. This module allows you to interact with web services in SOAP quickly and easily.

After installing the soap module, you can create a new SOAP client instance by passing as a parameter the URL of the web service. For example, the following code creates a new SOAP client for the web service at http://www.example.com/Service.asmx:


'use strict';

const soap = require('soap');
const url = 'http://www.example.com/Service.asmx?WSDL';

soap.createClient(url, (err, client) => {
    if (err) throw err;
    console.log(client.describe());
});

Once the SOAP client has been created, it is possible to send a request to the web service using the call() method of the client. For example, the following code sends a request to the HelloWorld method of the web service:


'use strict';

const soap = require('soap');
const url = 'http://www.example.com/Service.asmx?WSDL';

soap.createClient(url, (err, client) => {
    if (err) throw err;
    client.HelloWorld((err, result) => {
        if (err) throw err;
        console.log(result);
    });
});

In this example, the response from the web service is passed to the callback function as a result parameter. There response is a JavaScript object that contains the data returned by the web service.

It is also possible to send parameters to the web service using the call() method. For example, the following code sends a request to the web service's Add method, passing the a and b parameters:


'use strict';

const soap = require('soap');
const url = 'http://www.example.com/Service.asmx?WSDL';

soap.createClient(url, (err, client) => {
    if (err) throw err;
    const args = {a: 5, b: 10};
    client.Add(args, (err, result) => {
        if (err) throw err;
        console.log(result);
    });
});

In this example, the parameters are passed to the web service as a JavaScript object.

If you want to avoid the excessive use of callback functions, you can use the util method. promisify() of Node.js to use Promises, as all the functions seen follow the error-first callback pattern.