How to consume SOAP service in Node.js
Today we’ll show you how to consume SOAP service in Node.js. When you are working with the large scale application where you may need to use the third party application through SOAP web service. So we decide to share the small example to consume SOAP API in Node.js.
In the previous articles, we have explained about the creation of the REST API in Node.js and integration of the REST API in SPA such as React, Angular, Vue, etc..
Consume SOAP service in Node.js
1. Sample SOAP service
First of all, we will take a sample SOAP web service to consume from the Node environment. Let’s look at how this SOAP call might be structured.
Request URL
http://www.example.com/exampleapi
XML Request Template
<!--?xml version="1.0"?-->
<soap:envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:header>
</soap:header>
<soap:body>
<getuser>
<userid>123456</userid>
</getuser>
</soap:body>
</soap:envelope>
XML Response Template
<soap:envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/" soap:encodingstyle="http://www.w3.org/2003/05/soap-encoding">
<soap:body>
<getuserresponse>
<username>Clue Mediator</username>
</getuserresponse>
</soap:body>
</soap:envelope>
2. Add npm dependency
Here, we will use the easy-soap-request npm package to make SOAP requests easier via Node.js. Run the following command to install the npm dependency.
npm i easy-soap-request
3. Perform SOAP request
After successful installation of the npm package, perform the SOAP request by adding the following code snippets.
const soapRequest = require('easy-soap-request');
...
...
// Example data
const url = 'http://www.example.com/exampleapi';
const sampleHeaders = {
'Content-Type': 'text/xml;charset=UTF-8'
};
const xml = `<!--?xml version="1.0"?-->
<soap:envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:header>
</soap:header>
<soap:body>
<getuser>
<userid>123456</userid>
</getuser>
</soap:body>
</soap:envelope>
`;
// usage of module
(async () => {
const { response } = await soapRequest({ url: url, headers: sampleHeaders, xml: xml });
console.log(response.body);
/* Example output:
<soap:envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/" soap:encodingstyle="http://www.w3.org/2003/05/soap-encoding">
<soap:body>
<getuserresponse>
<username>Clue Mediator</username>
</getuserresponse>
</soap:body>
</soap:envelope>
*/
})();
4. Output
When executing the above code, you will get the output specified in the response of the SOAP request. You will also receive the `headers` and `statusCode` along with the response from the `soapRequest`.
You can also check the same SOAP web service from the postman to verify it.
That’s it for today.
Thank you for reading. Happy Coding..!!