【发布时间】:2020-09-13 14:38:52
【问题描述】:
我一直在尝试从 NewsAPI.org 获取文章,但出现此错误:
Access to XMLHttpRequest at 'https://newsapi.org/v2/top-headlines?country=us&category=general&apiKey=XXXXXXXXXXXXX' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我注意到它在就绪状态 4 和状态 0 处停止。
这是我使用的函数的代码:
function getNews()
{
var url = 'https://newsapi.org/v2/top-headlines?country='+country+'&category='+category+'&apiKey=XXXXXXXXXXXXX';
var req = new XMLHttpRequest();
req.open('GET' , url);
req.send();
req.onreadystatechange = function()
{
if(req.readyState == 4 && req.status == 200)
{
news = JSON.parse(req.response);
news = news.articles;
displayNews();
}
}
}
注意:我尝试添加“Access-Control-Allow-Origin”标头,但没有任何改变。
【问题讨论】:
标签: javascript api get xmlhttprequest