Javascript 为什么我对API的请求会给我这个错误

Javascript 为什么我对API的请求会给我这个错误,javascript,api,cors,Javascript,Api,Cors,Im尝试访问连接到好友系统API的数据。 我使用postman生成请求,然后将其复制到代码中。 我希望能够访问不同对象的字段 我已经尝试为chrome安装cors扩展 下面是我如何在脚本中提出请求 var request = new XMLHttpRequest() request.open('GET','http://controlforestal.pablocanales.info/api/trozos?total=100&limit=100&offset=0&

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

我已经尝试为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。这允许您的服务器(在本例中我假设为localhost)向第三方API库(在本例中为controlforestal)发出API请求。有关更多详细信息,请参阅CORS文档。

您可以在下面找到使用XMLHttpRequest的CORS实现:


根据您使用CORS的项目,您还可以使用预处理api请求,它应该为您完成这项工作。

因为
controlforestal.pablocanales.info
不希望您从客户端(浏览器)访问它的资源-CORS就是这样做的,它保护资源不被“借用”在网页中是您的网页来自服务器(本地或其他)还是使用
文件://
协议?我从问题中删除了您的令牌。一般来说,把这种敏感信息放在公共场合是个坏主意。为了弥补这一点,我将API中的响应头添加到了您的问题中。错误消息非常清楚。它需要一个不存在的头。当然,您假定OP拥有
controlforestal.pablocanales.info
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