0

I'm trying to send a https request from a HbbTV-Application (xhtml) to get information from https://www.meethue.com/api/nupnp.

XMLHttpRequest was my first option, but due to same origin policy it obviously won't work. As an alternative i found CORS, but as I understand it it needs XMLHttpRequest2, which is part of HTML5, am I correct?

Is there any function, method or workaround I could use to achieve my goal?

Best regards Adrian

4

1 回答 1

2

XMLHttpRequest 是我的第一选择,但由于相同的来源政策,它显然行不通。

我不明白。

从这里在 stackOverflow 上,我使用以下代码片段在您提供的端点上运行 XHR 没有问题:

function fetchData() {
  var URL = 'https://www.meethue.com/api/nupnp';
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
      if (xhr.readyState == XMLHttpRequest.DONE) {
        document.getElementById('response')
          .innerHTML = "Response: " + xhr.responseText
      }
  }
  xhr.open('GET', URL)
  xhr.send()
}
<div id='response' onclick='fetchData()'>Click to fetch</div>

CORS(跨域资源共享)本身与其说是一种技术,不如说是一种规范。

它定义了仅当目标端点指定允许源在该处获取时才应允许跨源请求。如果你想了解更多,我推荐 MDN 上的这篇优秀文章:HTTP Access Control (CORS)

此外,如果您的平台支持它或者您可以填充它,我建议您使用 Fetch 而不是 XHR。

于 2017-09-07T12:22:01.133 回答