How to fix uncaught TypeError Failed to construct 'Headers': Invalid name at getNews , I'm using newsapi

576 Views Asked by At

I'm trying to make a basic project using newsapi.org, but I'm getting an err of:

Uncaught TypeError: Failed to construct 'Headers': Invalid name
    at getNews (index.js:4:16)
    at HTMLButtonElement.onclick 

& Unchecked runtime.lastError: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received.

`

function getNews() {
  fetch(
    "https://cors-anywhere.herokuapp.com/https://newsapi.org/v2/top-headlines?country=us&apiKey=<My ApiKey>",
    { headers: new Headers({ "X-Requested With": "abcd" }) }
  )
    .then((a) => a.json())
    .then((response) => {
      for (let i = 0; response < response.articles.length; i++) {
        document.getElementById("output").innerHTML +=
          "<div class='article'> <img class='image' src='+response.articles[i].urlToImage+' > </div> <h1>" +
          response.articles[i].title +
          "</h1>" +
          response.articles[i].source.name +
          "<br>" +
          response.articles[i].description +
          "<a href=" +
          response.articles[i].url +
          "target='_blank'>" +
          response.articles[i].url +
          "</a></div>";
      }
    });
}

I think problem is with innerHTML.

<body>
    <button class="btn" onclick="getNews()">Get News Here.</button>
    <div class="output"></div>
    <script src="index.js"></script>
  </body>

`

I was hoping to see the news articles load dynamically but instead had this error!!

1

There are 1 best solutions below

3
kanvil On
Failed to construct 'Headers': Invalid name

The reason for this error is because With is separated by a space in the X-Requested With header.

 new Headers({ "X-Requested With": "..." }) }

You must write with a hyphen(-). Replace with X-Requested-With