Search code examples
xmlnode.jssoaptypeerrornode-soap

TypeError when trying to call National Rail SOAP API via Node


I'm trying to access the National Rail API using node-soap.

Documentation is here: https://lite.realtime.nationalrail.co.uk/OpenLDBWS/

I am new to SOAP so this might not be an issue with the API. I am getting a TypeError with whatever I attempt...

TypeError: Cannot read property 'Body' of undefined

Here is the code I am using to try and make a call:

var soap = require('soap');
var url = 'https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx?ver=2014-02-20';
var soapHeader = '<com:AccessToken>MY_TOKEN</com:AccessToken>';

soap.createClient(url, function(err, client){

  var args = {
    numRows : 10,
    crs : 'LAN'
  };

  client.addSoapHeader(soapHeader);

  client.GetDepartureBoard(args, function(err, result){
    if(err){
      console.log('error!');
      throw err;
    }
    console.log(result);
  });  
});

Using node-soap I can also get the request envelope, this is the contents:

<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tns="http://thalesgroup.com/RTTI/2014-02-20/ldb/"
    xmlns:tok="http://thalesgroup.com/RTTI/2013-11-28/Token/types"
    xmlns:ct="http://thalesgroup.com/RTTI/2007-10-10/ldb/commontypes"
    xmlns:ldbt="http://thalesgroup.com/RTTI/2012-01-13/ldb/types"
    xmlns:ldbt2="http://thalesgroup.com/RTTI/2014-02-20/ldb/types">
    <soap:Header>
        <com:AccessToken>MY_TOKEN</com:AccessToken>
    </soap:Header>
    <soap:Body>
        <tns:GetDepartureBoardRequest
            xmlns:tns="http://thalesgroup.com/RTTI/2014-02-20/ldb/"
            xmlns="http://thalesgroup.com/RTTI/2014-02-20/ldb/">
            <tns:numRows>10</tns:numRows>
            <tns:crs>LAN</tns:crs>
        </tns:GetDepartureBoardRequest>
    </soap:Body>
</soap:Envelope>

Solution

  • Your soap header was formatted incorrectly, it needs '<'AccessToken'>''<'/AccessToken'>' wrapped around it

    var args, soap, soapHeader, url;
    
    soap = require('soap');
    
    url = 'https://lite.realtime.nationalrail.co.uk/OpenLDBWS/wsdl.aspx?ver=2014-02-20';
    
    soapHeader = '<AccessToken><TokenValue>Your access token</TokenValue></AccessToken>'
    
    // or you can write it as an object
    //soapHeader = {
    //    AccessToken: {
    //        TokenValue: "Your access token"
    //    }
    //};
    
    args = {
        numRows: 10,
        crs: 'BSK'
    };
    
    soap.createClient(url, function(err, client) {
        client.addSoapHeader(soapHeader);
        return client.GetArrivalDepartureBoard(args, function(err, result) {
            return console.log(JSON.stringify(result));
        });
    });