【发布时间】: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