How to Make a SOAP Request with Node.js using raw XML

There are libraries out there that you can use to make SOAP requests from Node.js. But I really just wanted to throw raw XML at my SOAP service. None of the libraries seemed to be able to do that, so I’m using the Node.js http implementation.

var http = require('http');
var http_options = {
  hostname: 'localhost',
  port: 80,
  path: '/LocationOfSOAPServer/',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': xml.length
  }
}

var req = http.request(http_options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });

  res.on('end', () => {
    console.log('No more data in response.')
  })
});

req.on('error', (e) => {
  console.log(`problem with request: ${e.message}`);
});

// write data to request body
req.write(xml); // xml would have been set somewhere to a complete xml document in the form of a string
req.end();

This code is almost exactly what’s in the Node.js documentation. Obviously you can send any sort of POST data to any web server, or submit GET requests. Node.js uses this http implementation rather than what Javascript uses, which is XMLHttpRequest.

Share Button

2 Comments

Vern

This is great. I am working on a project in Node that requires making an http POST request. What is the chunk variable? Is that were you pass the body data?

Keith Vance

The chunk variable is handling the SOAP service response. I’m just writing to console.log, but you could do whatever you need to with it.

Comments are closed.