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>
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 -->
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.
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)}); }
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.