12

I'm new for coding, currently i'm exploring on Axios to send XML request, appreciate for your help on how to translate below into Axios command?

Request body

<?xml version="1.0" encoding="UTF-8"?>
<req:KnownTrackingRequest xmlns:req="http://www.example.com" 
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                    xsi:schemaLocation="http://www.example.com
                    TrackingRequestKnown.xsd">
<Request>
    <ServiceHeader>
        <MessageTime>2002-06-25T11:28:56-08:00</MessageTime>
        <MessageReference>1234567890123456789012345678</MessageReference>
        <SiteID>SiteID</SiteID>
        <Password>Password</Password>
    </ServiceHeader>
</Request>
<LanguageCode>en</LanguageCode>
<AWBNumber>01234567890</AWBNumber>
<LevelOfDetails>LAST_CHECK_POINT_ONLY</LevelOfDetails>

Bharathvaj Ganesan
  • 3,054
  • 1
  • 18
  • 32
Adam
  • 135
  • 1
  • 1
  • 4
  • 2
    Possible duplicate of [Make request to SOAP endpoint using axios](https://stackoverflow.com/questions/45974831/make-request-to-soap-endpoint-using-axios) – Quentin Oct 30 '18 at 07:49
  • Also https://stackoverflow.com/questions/45066928/send-raw-payload-to-axios – Quentin Oct 30 '18 at 07:49

4 Answers4

19

You can use XML instead of JSON in axios as follows.

var xmlBodyStr = `<?xml version="1.0" encoding="UTF-8"?>
       <req:KnownTrackingRequest xmlns:req="http://www.example.com" 
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                xsi:schemaLocation="http://www.example.com
                TrackingRequestKnown.xsd">
         <Request>
           <ServiceHeader>
              <MessageTime>2002-06-25T11:28:56-08:00</MessageTime>
              <MessageReference>1234567890123456789012345678</MessageReference>
              <SiteID>SiteID</SiteID>
              <Password>Password</Password>
           </ServiceHeader>
         </Request>
         <LanguageCode>en</LanguageCode>
         <AWBNumber>01234567890</AWBNumber>
         <LevelOfDetails>LAST_CHECK_POINT_ONLY</LevelOfDetails>`;

var config = {
     headers: {'Content-Type': 'text/xml'}
};

axios.post('https://POST_URL', xmlBodyStr, config); 

below is my full code:

    const axios = require('axios');
const parseString = require('xml2js').parseString;
exports.handler = function(context, event, callback) {
var xmlBodyStr = `<?xml version="1.0" encoding="UTF-8"?>
   <req:KnownTrackingRequest xmlns:req="http://www.sample.com" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xsi:schemaLocation="http://www.sample.com
            TrackingRequestKnown.xsd">
     <Request>
       <ServiceHeader>
          <MessageTime>2002-06-25T11:28:56-08:00</MessageTime>
          <MessageReference>1234567890123456789012345678</MessageReference>
          <SiteID>ID</SiteID>
          <Password>Pwd</Password>
       </ServiceHeader>
     </Request>
     <LanguageCode>en</LanguageCode>
     <AWBNumber>0123456789</AWBNumber>
     <LevelOfDetails>LAST_CHECK_POINT_ONLY</LevelOfDetails>`;
var config = {
 headers: {'Content-Type': 'text/xml'}
};
 axios.post('https://xml.sample.com/XMLShippingServlet', xmlBodyStr, config).then(res => {
callback(res.data);
}).catch(err => callback(err));
};    

XML Response:

<?xml version="1.0" encoding="UTF-8"?>
<req:TrackingResponse xmlns:req="http://www.dhl.com" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.dhl.com TrackingResponse.xsd">
<Response>
    <ServiceHeader>
        <MessageTime>2018-11-02T04:29:21.024+01:00</MessageTime>
        <MessageReference>1234567890123456789012345678</MessageReference>
        <SiteID>ID</SiteID>
    </ServiceHeader>
</Response>
<AWBInfo>
    <AWBNumber>1234567890</AWBNumber>
    <Status>
        <ActionStatus>success</ActionStatus>
    </Status>
    <ShipmentInfo>
        <OriginServiceArea>
            <ServiceAreaCode>PEN</ServiceAreaCode>
            <Description>PENANG-MYS</Description>
        </OriginServiceArea>
        <DestinationServiceArea>
            <ServiceAreaCode>PAO</ServiceAreaCode>
            <Description>Description</Description>
        </DestinationServiceArea>
        <ShipperName>Shipper</ShipperName>
        <ShipperAccountNumber>12354678</ShipperAccountNumber>
        <ConsigneeName>Sample</ConsigneeName>
        <ShipmentDate>2018-09-21T02:41:21</ShipmentDate>
        <Pieces>1</Pieces>
        <Weight>0.5</Weight>
        <WeightUnit>K</WeightUnit>
        <GlobalProductCode>P</GlobalProductCode>
        <ShipmentDesc>testing</ShipmentDesc>
        <DlvyNotificationFlag>N</DlvyNotificationFlag>
        <Shipper>
            <City>CHEMOR</City>
            <PostalCode>12345</PostalCode>
            <CountryCode>MY</CountryCode>
        </Shipper>
        <Consignee>
            <City>SUNNYVALE</City>
            <CountryCode>US</CountryCode>
        </Consignee>
        <ShipmentEvent>
            <Date>2018-09-21</Date>
            <Time>11:30:52</Time>
            <ServiceEvent>
                <EventCode>OK</EventCode>
                <Description>Delivered</Description>
            </ServiceEvent>
            <Signatory>Cnee</Signatory>
            <ServiceArea>
                <ServiceAreaCode>ABC</ServiceAreaCode>
                <Description>sample</Description>
            </ServiceArea>
        </ShipmentEvent>
    </ShipmentInfo>
</AWBInfo>
<LanguageCode>en</LanguageCode>
</req:TrackingResponse>
<!-- ServiceInvocationId:20181102042921_7837_c7ab8c82-428a-4b59-8379- 
a00ec8a4f29e -->
Adam
  • 135
  • 1
  • 1
  • 4
Bharathvaj Ganesan
  • 3,054
  • 1
  • 18
  • 32
  • @Adam can u post the errors so that it will be easy to solve – Bharathvaj Ganesan Nov 01 '18 at 07:44
  • Hi Bharathvaj, error as below: { message: 'err is not defined', name: 'ReferenceError', stack: 'ReferenceError: err is not defined\n at Object.exports.handler (/var/task/handlers/ZFbd2cc588b7f69f214638d61d65ec7b8a.js:24:10)\n at Object.exports.handler (/var/task/node_modules/enigma-lambda/index.js:306:10)\n at exports.handler (/var/task/enigma.js:17:9)' } – Adam Nov 01 '18 at 07:46
  • @Adam it says `err` variable is not defined. I'have updated the code. – Bharathvaj Ganesan Nov 01 '18 at 08:08
  • This has nothing to do with Axios and XML – Bharathvaj Ganesan Nov 01 '18 at 08:09
  • Hi Bharathvaj, thanks for the guidance, t's working now. How do i use Axios function to capture the XML response and parse to JSON? i updated the xml response file after the script. – Adam Nov 02 '18 at 03:38
  • `var parseString = require('xml2js').parseString; axios.get('URL') .then(response => { parseString(response.data, function (err, result) { //access your xml data as join here }); }) }` @Adam this way u can convert xml to json. – Bharathvaj Ganesan Nov 02 '18 at 04:08
  • Hi Bharathvaj, i received above xml response under "Body" and the Content Type is text. How can i use axios to read the body contents and then convert to JSON? Truly appreciate for your patience. – Adam Nov 02 '18 at 06:19
  • Hi Bharathvaj, how do access my xml data as join? – Adam Nov 15 '18 at 05:37
1
const axios = require('axios')
const qs = require('querystring')

...

const requestBody = {
  name: 'Akexorcist',
  age: '28',
  position: 'Android Developer',
  description: 'birthdate=25-12-1989&favourite=coding%20coding%20and%20coding&company=Nextzy%20Technologies&website=http://www.akexorcist.com/',
  awesome: true
}

const config = {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
}

axios.post(url, qs.stringify(requestBody), config)
  .then((result) => {
    // Do somthing
  })
  .catch((err) => {
    // Do somthing
  })

You need to encode XML data using querystring.

Zhong Ri
  • 2,556
  • 1
  • 19
  • 23
1

This code is working, I have developed a web app client reactjs that consume a soap web service from spring boot, look at the code and take what you want, I have also commented my code, so it will be more clear.

let xmls='<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"\
            xmlns:web="http://spring.io/guides/gs-producing-web-service">\
            <soap:Header/>\
                <soap:Body>\
                <web:loginVerified>\
                    <login>'+credentials.username+'</login>\ //if you wanna send dynamic vlaue to the soap service
                    <pass>'+credentials.password+'</pass>\
                </web:loginVerified>\
                </soap:Body>\
            </soap:Envelope>';

axios.post('http://localhost:8585/AdminWS?wsdl',
           xmls,
           {headers:
             {'Content-Type': 'text/xml'}
           }).then(res=>{
            var parseString = require('xml2js').parseString; //here i'm using a library colled xml2js to parse the respanse from xml to js object
            var stripNS = require('xml2js').processors.stripPrefix;
            const options = {
                tagNameProcessors: [stripNS],
                explicitArray: false
            };
            parseString(res.data, options, function (err, result) {
                
                console.log(result.Envelope.Body.loginVerifiedResponse.return);//get the value from the respanse object

            });
           }).catch(err=>{alert(err)});
   }
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Hamza AZIZ
  • 2,582
  • 1
  • 9
  • 18
0

An alternative to the other answers is to use xml2js for serializing a typescript class to XML instead of working with the raw XML syntax. Here is an example.

import { Builder } from 'xml2js';

...

    postBundleAssets():Observable<AxiosResponse> {
        const httpsAgent = new https.Agent({ rejectUnauthorized: false });
        let data = this.buildSampleMessage()
        let requestUrl:string = this.baseUrl + "/bundles/assets";
        return this.httpService.post(requestUrl,data,
            { 
                withCredentials: true,
                maxRedirects: 0,
                httpsAgent: httpsAgent,
                headers: {
                    cookie: this.cookieJar.myCookies,
                    'Content-Type': 'application/xml'
                },
            }
        )
    }

    buildSampleMessage() {
        let message: string;
        let assetDoc: AssetDoc = new AssetDoc()
        assetDoc.doc = new AssetDocRoot()
        let asset1: Asset = new Asset();
        asset1.$.ID="a5"
        asset1.$.class="$XxxAtlas-HiveDb"
        asset1.$.repr="HiveDb3"
        let qualifiedNameAttribute:Attribute = new Attribute()
        let nameAttribute:Attribute = new Attribute()
        let clusterNameAttribute:Attribute = new Attribute()
        qualifiedNameAttribute.$.name="$qualifiedName"
        qualifiedNameAttribute.$.value="host1.HiveDb3"
        nameAttribute.$.name="name"
        nameAttribute.$.value="HiveDb3"
        clusterNameAttribute.$.name="$clusterName"
        clusterNameAttribute.$.value="Cluster1"
        asset1.attribute = []
        asset1.attribute.push(qualifiedNameAttribute)
        asset1.attribute.push(nameAttribute)
        asset1.attribute.push(clusterNameAttribute)
        assetDoc.doc.assets = new AssetList()
        assetDoc.doc.assets.asset = []
        assetDoc.doc.assets.asset.push(asset1)
        assetDoc.doc.importAction = new ImportAction()
        assetDoc.doc.importAction.$.completeAssetIDs = "a5"
        let builder:Builder = new Builder()
        message = builder.buildObject(assetDoc)
        console.log(message)
        return message;
    }

Here is an example of a typescript dto class:

import { Attribute } from "./attribute";
import { Reference } from "./reference";

export class Asset {
    $: AssetAttributes = new AssetAttributes()
    attribute: Attribute[];
    reference: Reference[];
}

class AssetAttributes {
    class:string;
    repr:string;
    ID:string;
}

The generated XML looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<doc xmlns="http://www.ibm.com/iis/flow-doc">
  <assets>
    <asset ID="a5" class="$XxxAtlas-HiveDb" repr="HiveDb3">
      <attribute name="$qualifiedName" value="host1.HiveDb3"/>
      <attribute name="name" value="HiveDb3"/>
      <attribute name="$clusterName" value="Cluster1"/>
    </asset>
  </assets>
  <importAction completeAssetIDs="a5"/>
</doc>
nize
  • 1,012
  • 1
  • 11
  • 27