简体   繁体   English

如何使用JavaScript从API获取XML响应?

[英]How to get XML response from API using JavaScript?

I am trying to get Petrol Prices from Global Petrol Prices, their API has XML as response. 我正在尝试从“全球汽油价格”中获取汽油价格,其API具有XML作为响应。 This is code to get XML Response. 这是获取XML响应的代码。

var apiURL =
  'https://www.globalpetrolprices.com/api/getGasXML_weekly.php?gasoline_diesel=2&rate=USD&countries=52&p=765982d8f9f5f25d4dafc14aa38922f2';

fetch(apiURL, {
  method: 'GET',
  mode: 'no-cors'
})
  .then(response => response.text())
  .then(str => new window.DOMParser().parseFromString(str, 'text/xml'))
  .then(data => console.log(data));

But I am not getting any response from the code. 但是我没有从代码中得到任何回应。 However, when I visit to that URL I get XML response like this. 但是,当我访问该URL时,会得到如下XML响应。

<mtc:data><mtc:country id="DZ" country_name="Algeria">
 <mtc:gas_type id="diesel">0.2</mtc:gas_type>
 <mtc:year>2018</mtc:year>
 <mtc:week>34</mtc:week>
 <mtc:week_start>20-08-2018</mtc:week_start>
 <mtc:currency>USD</mtc:currency></mtc:country>
</mtc:data>

Can anyone help me with this? 谁能帮我这个? TIA TIA

If you send a request with JavaScript on the client side, you get an error. 如果您在客户端使用JavaScript发送请求,则会收到错误消息。 No 'Access-Control-Allow-Origin' header is present on the requested resource. 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 you will get the error 你会得到错误

You have to do by Server side 你必须在服务器端做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在JavaScript中存储通过使用api获得的XML响应? - How to store the XML response that we got from using an api in javascript? 如何在 JavaScript 中解析来自 API 的 XML 响应? - How to parse XML response from API in JavaScript? 如何从 API 获取响应数据并从数据中编码函数以使用 node js JavaScript 获取结果 - How to get the response data from API and code the function from data to get the result using node js JavaScript 如何从请求 API 获取响应数据 XML? - How to Get Response Data XML From Request API? 解析来自API,Javascript,Ajax的XML响应 - Parse XML response from API, Javascript, Ajax 如何在 Cypress 中使用 JavaScript 在 GET API 的请求正文中发送 XML。 以 JSON 格式发送请求会给出响应,因为输入格式不正确 - How to send XML in request body of a GET API using JavaScript in Cypress. Sending request in JSON format gives response as Input was not well formed 如何使用javascript从XML获取元素 - how to get element from XML using javascript 如何使用Javascript从API获得大响应的一部分? - How can I get portions of a big response from an API using Javascript? 如何从Javascript到PHP文件获得Payeezy API响应? - How to get Payeezy API response from Javascript to PHP file? 如何从 javascript Fetch api 获取可读错误响应? - How to get Readable error response from javascript Fetch api?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM