Mi código funciona en el servidor en vivo del código VS, pero cuando lo alojé en las páginas de Github, me dio un error. Parece funcionar bien y todo mi código parece funcionar y no encontré ningún error.
// 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();Eche un vistazo a la consola, obtiene el siguiente error:
{"status":"error","code":"corsNotAllowed","message":"Requests from the browser are not allowed on the Developer plan, except from localhost."}Si desea utilizar esta API fuera de su computadora, debe comprar una licencia.
Está recibiendo este error porque los artículos no se obtienen por completo antes de que se ejecute el método forEach , por lo que
console.log(articles);//undefined es undefined Asegúrese de que sus datos de API se obtengan por completo antes de usar forEach . Puede usar async await o promise para obtener datos de api.