JAVASCRIPT
Integrate with Legacy SOAP APIs using Node.js
Discover how to consume and interact with a SOAP web service from a Node.js backend application using a dedicated SOAP client library, handling WSDL and XML.
const soap = require('soap'); // Install with: npm install soap
// URL to the WSDL file of the SOAP service
const WSDL_URL = 'http://www.dneonline.com/calculator.asmx?WSDL'; // Example public calculator SOAP service
async function callSoapService() {
try {
// Create a SOAP client from the WSDL URL
const client = await soap.createClientAsync(WSDL_URL);
console.log('SOAP client created successfully.');
// If the SOAP service requires security (e.g., WS-Security username token), you can add it:
// client.setSecurity(new soap.WSSecurity('username', 'password', { passwordType: 'PasswordText' }));
// You can inspect the service methods and arguments
// console.log('Service description:', client.describe());
// Prepare arguments for the SOAP method call
const addArguments = {
intA: 10,
intB: 5,
};
// Call a specific method on the SOAP service.
// The method name is usually found in the WSDL.
// The callback signature is (err, result, rawResponse, soapHeader, rawRequest)
const [addResult] = await client.AddAsync(addArguments);
console.log(`Result of Add(10, 5): ${addResult.AddResult}`);
const multiplyArguments = {
intA: 10,
intB: 5,
};
const [multiplyResult] = await client.MultiplyAsync(multiplyArguments);
console.log(`Result of Multiply(10, 5): ${multiplyResult.MultiplyResult}`);
} catch (error) {
console.error('Error integrating with SOAP service:', error.message);
if (error.response) {
console.error('SOAP Response Status:', error.response.status);
console.error('SOAP Response Data:', error.response.data);
}
}
}
// Execute the SOAP call
callSoapService();
How it works: This Node.js snippet demonstrates how to integrate with a legacy SOAP API using the `node-soap` library. It starts by creating a SOAP client from a Web Services Description Language (WSDL) URL, which defines the available services, operations, and message structures. The snippet then shows how to call a specific SOAP method (e.g., `Add` or `Multiply`) with the required arguments and process the XML-based response, providing a robust way to interact with older web services.