Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML request and response with fetch?

The Postal Service has an API that allows you to send an xml request with package weight, travel info, etc. It will return back an xml response.

How do I handle the xml response? I either need to parse the xml on the client-side, or more preferably, put the xml in a variable that I can send to my laravel backend for parsing.

Btw, I'm using react and 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));
}
like image 778
JasparLamarCrab Avatar asked Dec 13 '22 22:12

JasparLamarCrab


1 Answers

Response.text() returns a Promise, chain .then() to get the Promise value of .text() call.

If you are expecting a Promise to be returned from getPostagePrice function, return fetch() call from 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));
}
like image 89
guest271314 Avatar answered Dec 21 '22 10:12

guest271314