如何使用 Axios 库发送 XML 数据

Posted

技术标签:

【中文标题】如何使用 Axios 库发送 XML 数据【英文标题】:How to send XML data using Axios Library 【发布时间】:2019-04-03 04:05:13 【问题描述】:

我是编码新手,目前我正在探索 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>

【问题讨论】:

Make request to SOAP endpoint using axios的可能重复 还有***.com/questions/45066928/send-raw-payload-to-axios 【参考方案1】:

你可以在 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 -->

【讨论】:

@Adam 能把错误贴出来方便解决 嗨 Bharathvaj,错误如下: 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 在 Object.exports.handler (/var/task/node_modules/enigma-lambda/index.js:306:10)\n 在 exports.handler (/ var/task/enigma.js:17:9)' @Adam 它说err 变量未定义。我已经更新了代码。 这与axios和xml无关 您好 Bharathvaj,感谢您的指导,现在可以使用了。如何使用 Axios 函数捕获 XML 响应并解析为 JSON?我在脚本之后更新了 xml 响应文件。【参考方案2】:
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 数据进行编码。

【讨论】:

【参考方案3】:

这段代码正在运行,我开发了一个 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));
   

【讨论】:

以上是关于如何使用 Axios 库发送 XML 数据的主要内容,如果未能解决你的问题,请参考以下文章

axios怎么发送xml数据

Axios 如何取消已发送的请求?

如何使用 axios 发送数组和表单数据 - Vue

如何使用 axios get 请求发送正文数据和标头?

如何使用 axios 将文件和 JSON 数据一起发送到 API 端点?

如何使用 js 或 axios 将表单数据中的 url 作为文件发送