如何从 JSON 文件中获取数据,该文件位于没有 headers 的不同域中?

How can I get data from a JSON file that is on a different domain with no headers?

我正在尝试从 AWS JSON 获取数据。它不在我的域中,我无法获取数据。 chrome 给出的错误如下 任何人都可以查看我的代码并给我一些提示吗?

其次,我只是使用 link 使用 Insomnia,并且能够使用 $.0.Ed0320 获得我想要的特定数据点。我如何将其翻译成 JavaScript.

我试过使用 xmlHttpRequest。

这是JSON:

[
  {
    "Ed0320": "8.010886",
    "TmStamp": "2019-08-07 15:15:00",
    "Ed0340": "21.15973",
    "Ed0305": "0.2966875",
    "Ed0313": "3.344086"
  },
  {
    "Ed0320": "6.761719",
    "TmStamp": "2019-08-07 15:10:00",
    "Ed0340": "17.47292",
    "Ed0305": "0.2349026",
    "Ed0313": "2.789934"
  }
]

这是我的 XML:

function reqListener() {
     // parse the the data
     var data = JSON.parse(this.responseText)
     // create an array from the required data (result.Stats -> watch the capital 'S')
     var mappedData = data[0];
     // display data
     document.getElementById('demo').innerHTML = mappedData.join()
}
function loadData(url) {
     var oReq = new XMLHttpRequest();
     oReq.addEventListener("load", reqListener);
     oReq.open("GET", url);
     oReq.send();
}

Chrome 给出了 Access to XMLHttpRequest at <fileName> from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

的错误

function calcUVI(Ed0305, Ed0313, Ed0320, Ed0340){
                total305=(Ed0305*0.8058)
                total313=(Ed0313*0.0887)
                total320=(Ed0320*0.0324)
                total340=(Ed0340*0.0131)
                UVI = total305 + total313 + total320 + total340
                return UVI
            }

此外,我想根据下面的这个函数更改 url。有没有办法将其输入到提取中?

function changeText(){
                var d = new Date();
                var year = d.getFullYear();
                var month = d.getMonth() + 1;
                var day = d.getDate();
                if (month <= 9){
                    month = '0'+month;
                }
                if (day <= 9){
                    day = '0'+day;
                }
                var dateTotal = year + month + day;
                url = "https://cors-escape.herokuapp.com/https://tepfsail50.execute-api.us-west-2.amazonaws.com/v1/report/metguv?rptdate=" + dateTotal;
                console.log(url);
            }


提前感谢您的帮助。我对这一切真的很陌生。

1。正在获取数据

我不太确定你想要实现什么,但这里有一个片段,

  1. cors-anywhere.herokuapp.com 发出请求以“代理”“目标”的查询 URL

  2. Returns 来自查询的 URL 的 Promise,所以我们可以等待它在代码的其他部分解析

  3. 过滤并映射生成的数据 - 我不明白您想从生成的数组中获取什么数据以及您想如何处理这些数据

// self calling function to wrap the await in
// an async function (so the await is not "top level")
(async function() {
  // waiting for the returned Promise to resolve
  // if you console.log() the data constant, then you'll
  // see that it's the full dataset (in JSON format) that you
  // got from simply calling the AWS URL
  const data = await fetchURL()

  // filtering the array for objects that have a key of "Ed0320"
  const filtered = data.filter(e => typeof e['Ed0320'] !== "undefined")
  // mapping the values of all "Ed0320" from the array
  const mapped = data.map(e => e['Ed0320'])

  // simple output, so you can check the values
  console.log(filtered);
  console.log(mapped)
})();

// fetch request using cors-anywhere
function fetchURL() {
  // creating the URL to be called:
  // first part is cors-anywhere, second part is
  // the real URL to be queried
  const url = 'https://cors-anywhere.herokuapp.com/https://tepfsail50.execute-api.us-west-2.amazonaws.com/v1/report/metguv?rptdate=20190807'

  // returning a Promise, as fetch() is an asynchron
  // function, so it's not resolved immediately
  return new Promise((resolve, reject) => {
    // using fetch() instead of the XMLHttpRequest()
    // fetch returns a Promise, so you can use .then() and
    // .catch() chained after it
    fetch(url)
      .then(r => {
        resolve(r.json())
      })
      .catch(err => {
        reject(err)
      })
  })
}

所以,您的代码有 CORS 个问题(CORS:Cross-Origin Resource Sharing), that had to be handled before you could get the data. I used the cors-anywhere on Heroku to overcome this obstacle. You can set your cors-anywhere service by installing the module from npm (here: https://www.npmjs.com/package/cors-anywhere)。

2。编辑:处理数据

答案已编辑,因为问题已用更多信息展开。

这个新代码片段确实根据 API 的结果计算了 UVI(URL 是根据当前日期动态生成的)。

请注意:

  • 您可以缩短所有函数(比如不要为您只需要一次计算的值创建变量,您只需要 return 结果 - 例如当前日期字符串或UVI 计算)

  • 修改了日期字符串的“创建”:我使用了字符串插值和 ('0' + d.getDate()).slice(-2) 强制使用两位数长月和日

  • 当你创建(设计)一个函数时尽量保持简单——它应该只做一件事(所以不要创建一个生成当前日期字符串并将其附加到查询字符串的函数.这样维护起来会容易很多

  • calcUVI() 函数通过解构调用它的数组元素来接收其参数。熟悉解构——这并不难,而且可以使您的代码更易于阅读和理解。 (你可以从这里开始:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

(async function() {
  // modified fetchURL() - the URL parameter is passed to
  // the API query function
  const data = await fetchURL(urlToQuery())

  // calling calcUVI() function with the first data
  // entry of the data array
  const UVI = calcUVI(data[0])

  // displaying result in the console
  console.log("UVI:", UVI)
})();

function fetchURL(url) {
  return new Promise((resolve, reject) => {
    // the url parameter is received when the function
    // is called - it's not a constant anymore
    fetch(url)
      .then(r => {
        resolve(r.json())
      })
      .catch(err => {
        reject(err)
      })
  })
}

// creating and returning the API URL dynamically -
// date string is added
function urlToQuery() {
  // the query URL base is here - and the date string
  // at the end is created dynamically
  return `https://cors-anywhere.herokuapp.com/https://tepfsail50.execute-api.us-west-2.amazonaws.com/v1/report/metguv?rptdate=${getDateString()}`
}

// creating and returning the date string
function getDateString() {
  const d = new Date();
  return `${d.getFullYear()}${('0' + (d.getMonth() + 1)).slice(-2)}${('0' + d.getDate()).slice(-2)}`
}

// calcUVI receives the parameters destructured from
// the first element of the array (it's called in
// the main async function)
function calcUVI({
  Ed0305,
  Ed0313,
  Ed0320,
  Ed0340
}) {
  // no need to store these elements as variables, as the single
  // Ed... values are not used anymore in the process (a
  // total is returned, so just add them up)
  return Ed0305 * 0.8058 + Ed0313 * 0.0887 + Ed0320 * 0.0324 + Ed0340 * 0.0131
}