My code works in the live server of VS code but when I hosted it on Github pages it gave me and error. It seems to work fine and all of my code seems to work and I found no errors whatsoever.
// news parameters
const Api_Key = "...";
const category = "crypto";
const url = "https://newsapi.org/v2/top-headlines"
// https://newsapi.org/v2/top-headlines?q=crypto&apiKey=4d2ac6c2f603440a864065a48836b9f7
let newsAccordian = document.getElementById('newsAccordian')
// grab the new container
const xhr = new XMLHttpRequest()
xhr.open('GET', `${url}?q=${category}&apiKey=${Api_Key}`, true)
xhr.onload = function () {
let json = JSON.parse(this.responseText)
let articles = json.articles
console.log(articles) // error is shown in this line
let allNews = ""
articles.forEach(function(news,index) {
let newsContent = news.content.substring(0, news.content.length - 14);
}
xhr.send();
Have a look at the console, you get the following error:
{"status":"error","code":"corsNotAllowed","message":"Requests from the browser are not allowed on the Developer plan, except from localhost."}
If you want to use this api outside your computer, you have to purchase licence.
You are getting this error because articles is not fetched completely before forEach method execute so
console.log(articles);//undefined
is undefined. Make sure your data from api is fetched completely before using forEach. You can use async await or promise to fetch data from api.