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!!
The reason for this error is because
Withis separated by a space in theX-Requested Withheader.You must write with a hyphen(
-). Replace withX-Requested-With