如何使用Axios库发送XML数据

时间:2018-10-30 06:50:24

标签: javascript xml schema axios

我是编码新手,目前我正在Axios上探索发送XML请求,感谢您在下面将其转换为Axios命令方面的帮助?

请求正文

<?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>

3 个答案:

答案 0 :(得分: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
  })

您需要使用查询字符串对XML数据进行编码。

答案 1 :(得分:0)

可以在axios中使用XML而不是JSON,如下所示。

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); 

下面是我的完整代码:

    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响应:

<?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 -->

答案 2 :(得分:0)

这段代码是有效的,我开发了一个 web 应用客户端 reactjs,它从 spring boot 使用了一个soap web 服务,查看代码并获取你想要的,我也评论了我的代码,所以它会更清楚。

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)});
   }