0

Code :

async function getNews() {
    const response = await fetch('http://newsapi.org/v2/top-headlines?country=in&pageSize=1&apiKey=a876816f98574cdfa23ffdc7d531c7bc');
    const jsonResp = await response.json();
    return jsonResp;
}

n = await getNews();

Error Shown In Google Chrome Console:

Access to fetch at 'http://newsapi.org/v2/top-headlines?country=in&pageSize=1&apiKey=a876816f98574cdfa23ffdc7d531c7bc' from origin 'chrome-search://local-ntp' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

GET http://newsapi.org/v2/top-headlines country=in&pageSize=1&apiKey=a876816f98574cdfa23ffdc7d531c7bc net::ERR_FAILED getNews @ VM88:2 (anonymous) @ VM94:1

Uncaught TypeError: Failed to fetch

link to error image

Ramin eghbalian
  • 2,348
  • 1
  • 16
  • 36
  • Change the protocol from http to https and check , it says the request from browser are not allowed – Harmandeep Singh Kalsi Jun 21 '20 at 06:10
  • you seem to be hitting this url from your dev system, and API might have blocked the localhost server calls. try hitting this by deploying on some cloud server. – Manish Jun 21 '20 at 07:23

2 Answers2

0

Try using https://newsapi.org instead of http://newsapi.org as the endpoint.

  • check this answer https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors – Raj Kumar Jun 21 '20 at 06:17
  • Thank you for your reply. But after replaced http with https , I get new error : {status: "error", code: "corsNotAllowed", message: "Requests from the browser are not allowed on the Developer plan, except from localhost."} code: "corsNotAllowed" message: "Requests from the browser are not allowed on the Developer plan, except from localhost." status: "error" __proto__: Object – Md. Asif Iqbal Fahim Jun 21 '20 at 06:33
0

CORS are generally fixed by setting response headers at server side something like below

 res.header("Access-Control-Allow-Origin", "*");
 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

But temporary you can use chrome CORS plugin to get data from other host

aurabliss
  • 84
  • 5
  • Thank you for your response. From where I put this chunks of codes? – Md. Asif Iqbal Fahim Jun 21 '20 at 06:36
  • this has to be set at server side for response header, it seems you are using some 3rd party API(http://newsapi.org/v2/top-headlines) where you do not have any control. Try installing Allow CORS: Access-Control-Allow-Origin - Google Chrome plugin – aurabliss Jun 21 '20 at 07:19