2017-06-06 110 views
0

郵政服務有一個API,允許您發送包裹重量,旅行信息等XML請求。它會返回一個XML響應。XML請求和響應與提取?

如何處理xml響應?我需要在客戶端解析xml,或者更可取的是將xml放入一個變量中,我可以發送到我的laravel後端進行解析。

順便說一句,我正在使用反應和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)); 
} 
+0

讀取[抓取文檔】(https://developer.mozilla.org/en/docs/Web/API/Fetch_API)...通常你會'。然後((響應)=> response.text ())'然後下一個。然後文本可用......即用'return response.text()'替換'console.log(response.text())',以便**返回** –

+0

@JaromandaX注意,「something」是一個'Promise','.text()','.blob()','.arrayBuffer()',如果在環境中實現了'.formData()', 'Response'對象每個都返回一個'Promise' – guest271314

+0

我的觀點是,第一個.then根本沒有返回任何東西,並且確實表明它應該返回'response.text()' - 所以,不知道什麼點你正在試圖製作@ guest271314 –

回答

1

Response.text()返回Promise,鏈.then()得到.text()通話Promise值。

如果你期待一個PromisegetPostagePrice功能,從getPostagePrice()通話returnfetch()調用返回。

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

@JasparLamarCrab請參閱[如何讓用戶輸入顏色非十六進制或rbga)列表自定義,但確保它是有效的](https://stackoverflow.com/questions/44361825/how-to-allow-user-to-input-a-color-non-hex-or-rbga -for-list-customization-but/44362289#44362289)的類似模式 – guest271314