What is the proper way to execute this API request and retrieve the latest news data using the Fetch method?

Note: Please note that the API Key used in this code is not a real one for privacy reasons.

const url = 'http://newsapi.org/v2/everything?' +
          'q=platformer&' +
          'apiKey=3ce15c4d1fd3485cbcf17879bab498db';

async function getNews() {
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
}

getNews()

Upon running this Javascript code, I encounter an error:

Access to fetch at 'http://newsapi.org/v2/everything?q=platformer&apiKey=3ce15c4d1fd3485cbcf17879bab498db' from origin 'null' 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.

The main goal here is to fetch news data from newsapi.org and display it in the console.

Answer №1

The error message from the News API gives a clue:

Requests coming from the browser are restricted on the Developer plan, unless they originate from localhost

If you are running your application using a local development server (such as this one), simply switching your browser to http://localhost:8080/ instead of http://127.0.0.1:8080/ should do the trick:

https://i.stack.imgur.com/v798a.png

Below is a code snippet (to be executed locally with a webserver):

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>\
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>News</h1>

  <button id="btn-get">Get News</button>
  <div id="news-container"></div>
  <script>
    const url = `https://newsapi.org/v2/everything?q=bitcoin&apiKey=API_KEY`

    const newsContainer = document.getElementById('news-container')

    function fetchNews(url) {
      return fetch(url)
        .then(res => res.json())
    }

    document.getElementById('btn-get').addEventListener('click', () => {
      fetchNews(url)
        .then(articles => newsContainer.textContent = JSON.stringify(articles))
    })

  </script>

</body>

</html>

Answer №2

If you're looking to deal with Cross-Origin Resource Sharing (CORS) issues, one solution is to use a CORS Proxy.

For a more detailed explanation on CORS Proxies, check out this existing answer here. It provides a comprehensive walkthrough.


There's also a concise accepted answer specific to NewsApi.org available here.

Here's an excerpt:

You need a CORS proxy

const proxyUrl = "https://cors-anywhere.herokuapp.com/"
const qInTitle = "";
const from = "";
const apiKey = "";
const url = `${proxyUrl}https://newsapi.org/v2/everything?qInTitle=${qInTitle}&from=${from}language=en&apiKey=${apiKey}`;
const request = new Request(url);

fetch(request)
  .then(response => response.json())
  .then((news) => {
    console.log(news);
  })
  .catch(error => {
    console.log(error);
  });

And for a deeper dive into understanding CORS, this article from Mozilla might be helpful:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting Basic JSON Data into an SQL SELECT Query

Presented is the subsequent JSON data: DECLARE @json NVARCHAR(MAX) SET @json = N'[ {"@odata.context":"http://www.example.com","value":[ {"financialmovements_ID":1,"Data":"2020-02-10T00:00:00Z","ES":"E","Descri\u00e7\u00e3o":"FIV-005 3& ...

Is there a way to integrate a calendar feature within an Angular 2 application?

I am brand new to Angular 2 and have a question: I need to integrate a calendar into a page where users can add events. Something similar to the following example: I'm unsure if the angular material calendar project is designed for Angular 2 or for ...

Exploring the functionality of className using materialUI

Attempting to test whether my component has a specific class is proving challenging. This difficulty stems from the fact that the class is generated using MaterialUI. For instance, I am looking for a class named spinningIconCenter, but in reality, it appea ...

What is the process of incorporating a video into a react.js project through the use of the HTML

I'm experiencing an issue where my video player loads, but the video itself does not. Can anyone shed light on why this might be happening? class App extends Component { render() { return ( <div className="App& ...

Is it possible to bypass the confirmation page when submitting Google Form data?

Is there a way to bypass the confirmation page that appears after submitting a form? What I would like is for the form to simply refresh with empty data fields and display a message saying "your data has been submitted" along with the submitted data appea ...

What is the process for invoking a websocket from an HTML client?

I have created a WCF Service using netHttpBinding binding and it is hosted on IIS 8 (Windows Server 2012). The interfaces for the service are as follows: [ServiceContract(CallbackContract = typeof(IDuplexCallbackContract))] public interface IHelloWebSocke ...

Issues with jQuery AJAX functionality

I am in the process of incorporating some ajax functionality into my php website. I have a good understanding of jQuery, but for some reason, the value returned is always empty when I try to alert() it. Below is the code snippet that I am using: PHP: if( ...

Struggling with setting values in AngularJS?

Can you assist me in passing data from: (Page 1 -> Module 1 -> Controller 1) to (Page 2 -> Module 2 -> Controller 2) For example: Module reports - Controller ReportsCtrl //Page 1 <html lang="en" class="no-js" ng-app="reports"> <a ng-href="../n ...

Traversing an array of objects to extract and display the key-value pairs for each object

Here is an array I am working with: const cuisines = [ { african: "African" }, { american: "American" }, { arabian: "Arabian" }, { argentine: "Argentine" }, { asian: "Asian" }, { asian_fusion: "Asian Fusion" }, { australian: "Australi ...

What is the best way to add hidden columns in Telerik Grid MVC3?

I'm currently working with a grid where I need to hide certain columns using the following code: foreach (var attr in grid.Attr) .Columns(columns => { columns.Bound(attr.key) .Width(attr.width) .Visible(attr.isVisi ...

encounter with file compression using gzip

Currently, I am facing an issue with zipping files using jszip because the backend can only unzip gzip files, not zip files. My front end is built using vue.js. let zip = new jszip(); zip.file(fileToCompress.name, fileToCompress); let component = t ...

The AngularJS 2 TypeScript application has been permanently relocated

https://i.stack.imgur.com/I3RVr.png Every time I attempt to launch my application, it throws multiple errors: The first error message reads as follows: SyntaxError: class is a reserved identifier in the class thumbnail Here's the snippet of code ...

Access the system by logging in with a stored Google account

I have experience integrating "Login via Google account" on various websites. However, some sites like Zomato always display the option to login via Google as soon as you open them. They even show a list of Google accounts that I have previously logged i ...

The Resharper guideline "Function Parameter" doesn't allow the usage of AngularJS service names

I have a question regarding naming conventions in my AngularJS app. Currently, all my service names start with an uppercase character. However, I am facing an issue where service parameters must match the service name, but Resharper's JavaScript "Func ...

Begin the initial function again once the second function has been completed

I have 2 functions in my code: function DisplayAltText(){ var CurrentPhoto = $("#DisplayPhoto img").attr("src"); if( $.browser.msie ) { IECurrentPhoto (CurrentPhoto); } if ($(".PhotoGallery img[src='" +CurrentPhoto+ "&a ...

Switching between pages and updating the URL without needing to refresh the page, while still maintaining the content even after a refresh

After experimenting with jQuery's load() method to dynamically change content without refreshing the page, I encountered a recurring issue: the URL remains unchanged. Even when attempting to use history.pushState() to modify the URL, the problem pers ...

What is the best way to incorporate a condition within react material-ui components?

Currently I am constructing a generic data table using react and material-ui. My programming background is in c# and java, as well as some early experience with javascript. However, I am encountering syntax issues within reactjs. Here is the particular pi ...

Looking to align the labels of material UI tabs to the left instead of their default center alignment? Here's how

Is there a way to align material ui tab labels to the left instead of center by default? View an image demonstrating center aligned tab labels here ...

Dynamic Binding of ng-model to DOM Element in AngularJS

I am facing a challenge with my web page where I need to dynamically attach ng-model attributes to some HTML elements that I don't have the ability to edit. What I want to achieve is to have AngularJS re-bind these attributes to the scope. You can fin ...

Updating the parameters when clicking on each pagination button: A guide

Does anyone have advice on implementing pagination? I am currently working on loading a datatable with a few records initially. Once the page is loaded, I want to be able to click on pagination buttons like next or any pagination buttons to display a new s ...