简体   繁体   中英

Getting the CORS policy: No 'Access-Control-Allow-Origin' error

I am trying to integrate a third party API using JavaScript and its working fine on local but it is showing the error on live ie

Access to XMLHttpRequest at 'https://newsapi.org/v2/top-headlines?country=in&category=technology' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my JavaScript,

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj, i, x = "";
        myObj = JSON.parse(this.response);


        for (i=0;i<1;i++ in myObj.articles) {

            x += "<a href="+ myObj.articles[i].url +" target='blank'>"; 
            x += "<div style='background: linear-gradient(rgba(0,130,170,0),rgba(6,23,0,1)), url( "+ myObj.articles[i].urlToImage +" );height: 430px;margin-top: 20px;'>";          
            x += "</div>";          
            x += "</a>"; 

        }

        document.getElementById("technology").innerHTML = x;

    }
};

xmlhttp.open("GET", "https://newsapi.org/v2/top-headlines?country=in&category=technology", true);
xmlhttp.send();

HTML

<div style="background-color: gray;height: 430px;margin-top: 20px;">
   p id="technology"></p>
</div>

I don't understand why this is happening.

Please help me out, Thanks in advance.

The response is right in front of your eyes - You need to pay to use it outside of "localhost" domain which usually means you are develeping the site as developer thus you use the "Developer" plan. But when going live you need to pay up: 计划比较

And you clearly missing the API Key (if you havent cut it out to paste here;) ) in the request;)

As mentioned by @chris-g you are not using api-key. You might try with API key and perhaps CORS issue would be gone. If you are still getting CORS, try simple jquery $ajax with jsonp or try a simple proxy server to forward the request and response.

var proxy_url = 'https://cors-anywhere.herokuapp.com/';
var url = 'https://newsapi.org/v2/top-headlines?country=us&category=sports&pageSize=5&apiKey=<your-api-key>';

Now you can you use the proxy_url to avoid the CORS policy error by adding the proxy_url in front of your URL with the API-KEY

new_url = proxy_url + url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM