【问题标题】:GET XMLHttpRequest stops at readystate 4 and status 0GET XMLHttpRequest 在就绪状态 4 和状态 0 处停止
【发布时间】: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


    【解决方案1】:

    首先,xhr 请求没有在req.readystate == 4 停止,而是在res.send() 停止。另外CORS是浏览器提供的标准网络安全服务,用于防止数据从其他来源泄露。

    本地测试可以通过添加header绕过:

    Access-Control-Allow-Origin: *
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 2011-03-05
      • 2021-07-10
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      • 2011-07-15
      相关资源
      最近更新 更多