XML 使用 fetch 请求和响应?
XML request and response with fetch?
邮政服务 API 允许您发送包含包裹重量、旅行信息等的 xml 请求。它将 return 回复 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));
}
Response.text()
returns 一个 Promise
,链 .then()
以获得 .text()
调用的 Promise
值。
如果您希望从 getPostagePrice
函数返回 Promise
,请从 getPostagePrice()
调用 return
fetch()
调用。
getPostagePrice = () => {
fetch('/path/to/server')
.then(response => response.text())
.then(str => (new window.DOMParser()).parseFromString(str, "text/xml"))
.then(data => console.log(data));
}
此外,使用 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)
}
邮政服务 API 允许您发送包含包裹重量、旅行信息等的 xml 请求。它将 return 回复 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));
}
Response.text()
returns 一个 Promise
,链 .then()
以获得 .text()
调用的 Promise
值。
如果您希望从 getPostagePrice
函数返回 Promise
,请从 getPostagePrice()
调用 return
fetch()
调用。
getPostagePrice = () => {
fetch('/path/to/server')
.then(response => response.text())
.then(str => (new window.DOMParser()).parseFromString(str, "text/xml"))
.then(data => console.log(data));
}
此外,使用 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)
}