【问题标题】:Why is my request to an API giving me this error [duplicate]为什么我对 API 的请求给了我这个错误 [重复]
【发布时间】:2020-01-14 20:41:18
【问题描述】:

我正在尝试访问连接到好友系统 API 的数据。 我使用邮递员生成请求,然后将其复制到我的代码中。 我希望能够访问不同对象的字段

我已经尝试安装 chrome 的 cors 扩展。

这是我在脚本中提出请求的方式。

   var request = new XMLHttpRequest()

   request.open('GET','http://controlforestal.pablocanales.info/api/trozos?total=100&limit=100&offset=0&search=&status=&codigoOrigen=&largo=&diametro=&order-by=codigo&order-dir=desc&token=****', true)
request.onload = function() {
  // Begin accessing JSON data here
  var data = JSON.parse(this.response)
  if (request.status >= 200 && request.status < 400) {
data.forEach(trozo => {
  const card = document.createElement('div')
  card.setAttribute('class', 'card')

  const h1 = document.createElement('h1')
  h1.textContent = trozo.codigo

  container.appendChild(card)
  card.appendChild(h1)
})
  } else {
const errorMessage = document.createElement('marquee')
errorMessage.textContent = `error`
app.appendChild(errorMessage)
  }
}

request.send()

这是控制台显示的错误。

CORS 策略已阻止从源“null”访问“http://controlforestal.pablocanales.info/api/trozos?total=100&limit=100&offset=0&search=&status=&codigoOrigen=&largo=&diametro=&order-by=codigo&order-dir=desc&token=****”处的 XMLHttpRequest:请求的资源上不存在“Access-Control-Allow-Origin”标头。

标题是

HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Content-Type: application/json
X-Powered-By: PHP/5.5.9-1ubuntu4.21
Cache-Control: no-cache
Date: Thu, 12 Sep 2019 23:47:39 GMT
X-Frame-Options: SAMEORIGIN

【问题讨论】:

  • 因为 controlforestal.pablocanales.info 不希望您从客户端(浏览器)访问它的资源 - 这就是 CORS 所做的,它保护资源不被“借用”在网页中
  • 您的网页是来自服务器(本地或其他)还是使用file:/// 协议?
  • 我从问题中删除了您的令牌。将这种敏感信息放在公共帖子中通常是一个坏主意。为了弥补这一点,我将 API 中的响应标头添加到您的问题中。
  • 错误信息很清楚。它需要一个不存在的标头。

标签: javascript api cors


【解决方案1】:

根据您使用的服务器,您必须在服务器代码中启用 cors。这允许您的服务器(在本例中假设为 localhost)向第三方 API 库(在本例中为 controlforestal)发出 API 请求。有关更多详细信息,请参阅 CORS 文档。 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

您可以在下面找到使用 XMLHttpRequest 的 CORS 实现: https://www.html5rocks.com/en/tutorials/cors/

根据您使用 CORS 的项目,您还可以在您的 api 请求前添加 https://cors-anywhere.herokuapp.com/YOUR_API_URL_GOES_HERE,它应该可以为您完成这项工作。

【讨论】:

  • 你当然是假设 OP 拥有 controlforestal.pablocanales.info
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 2020-11-08
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
  • 2022-08-12
相关资源
最近更新 更多