XML请求和响应与提取?

Jas*_*rab 3 javascript fetch laravel reactjs

邮政服务有一个API,可让您发送包含包裹重量,旅行信息等的xml请求。它将返回xml响应。

如何处理xml响应?我或者需要在客户端解析xml,或者更可取的是,将xml放入一个可以发送到laravel后端进行解析的变量中。

顺便说一句,我正在使用react和laravel。

getPostagePrice = () => {
  fetch('http://production.shippingapis.com/ShippingApi.dll?API=RateV4&XML=<RateV4Request USERID="XXXXXXXXXXX"><PackageID="1ST"><Service>PRIORITY</Service><ZipOrigination>44106</ZipOrigination><ZipDestination>20770</ZipDestination><Pounds>1</Pounds><Ounces>8</Ounces><Container>NONRECTANGULAR</Container><Size>LARGE</Size><Width>15</Width><Length>30</Length><Height>15</Height><Girth>55</Girth></Package></RateV4Request>', {
       method: 'get',
   }).then((response) => {
       console.log(response.text());
   }).then(str => (new window.DOMParser()).parseFromString(str, "text/xml")
   ).then(data => console.log(data));
}
Run Code Online (Sandbox Code Playgroud)

gue*_*314 6

Response.text()返回一个Promise链,.then()以获取通话的Promise价值.text()

如果期望PromisegetPostagePrice函数返回a ,return fetch()请从getPostagePrice()call调用。

getPostagePrice = () => {
  fetch('/path/to/server')
  .then(response => response.text())
  .then(str => (new window.DOMParser()).parseFromString(str, "text/xml"))
  .then(data => console.log(data));
}
Run Code Online (Sandbox Code Playgroud)


Joa*_*era 5

另外,使用 async/await 您可以执行相同的操作,而不会丢失范围(请记住,如果您使用 .then,则只能在回调函数内工作)。

async function display(){     
    const xmlFetch = await fetch("./yourXMLorXSL.xml")
    const xmlText = await xmlFetch.text()
    const xml = await (new window.DOMParser()).parseFromString(xmlText, "text/xml")

    console.log(xml)
}
Run Code Online (Sandbox Code Playgroud)