【问题标题】:Getting Error with an API data when connecting to JAVASCRIPT连接到 JAVASCRIPT 时出现 API 数据错误
【发布时间】:2019-02-09 13:55:01
【问题描述】:

我一直在尝试使用 JavaScript 连接到一个 API,以完成一项我已经完成但无法完成的任务。每次我尝试运行一个文件时,它都会显示空白的 HTML 页面,但是在使用不同的 API 链接时,我的代码工作正常。

它显示的错误:

CORS 策略已阻止从源“null”访问“http://qa.parentlane.com/api/content-feed/”处的 XMLHttpRequest:“Access-Control-Allow-Origin”标头的值“https://www.parentlane.com”不等于提供的起源。 scripts.js:37

跨域读取阻塞 (CORB) 阻止了 MIME 类型为 application/json 的跨域响应 http://qa.parentlane.com/api/content-feed/。详情请见https://www.chromestatus.com/feature/5629709824032768

const app = document.getElementById('root');

const container = document.createElement('div');
container.setAttribute('class', 'container');

app.appendChild(container);

var request = new XMLHttpRequest();
request.open('GET', 'http://qa.parentlane.com/api/content-feed/', true);
request.onload = function () {

  var data = JSON.parse(this.response);
  if (request.status >= 200 && request.status < 400) {
    data.forEach(feed => {
      const card = document.createElement('div');
      card.setAttribute('class', 'card');

     const h1 = document.createElement('h1');
      h1.textContent = feed.title;

      const p = document.createElement('p');
      feed.text = movie.text.substring(0, 50);
      p.textContent = `${feed.text}...`;

      container.appendChild(card);
      card.appendChild(h1);
      card.appendChild(p);
    });
  } else {
    const errorMessage = document.createElement('marquee');
    errorMessage.textContent = `Gah, it's not working!`;
    app.appendChild(errorMessage);
 } 
 }

request.send();

结果应该会弹出一个类似网格的界面,其中包含 JSON 文件中的数据。

【问题讨论】:

    标签: javascript json api


    【解决方案1】:

    恐怕这是因为您尝试查询的目标主机不允许访问 除了自己。如果我看一下它的响应标头,它会说:

    access-control-allow-origin : https://www.parentlane.com
    

    这意味着尝试查询 api 的脚本和 api 需要位于同一主机上。 这是一篇深入的文章:

    https://developer.mozilla.org/de/docs/Web/HTTP/CORS

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 2019-01-08
      • 2020-04-04
      • 1970-01-01
      相关资源
      最近更新 更多