Uncaught (in promise) TypeError when trying to access a list of articles from NewsAPI

26 Views Asked by At

I am trying to create a news website which utilizes NewsAPI to fetch recent articles depending on the query. The end goal is that the user would be able to search up anything in the search bar, and it would list the recent articles that contain that search. You can see my attempt to implement the search feature by the end of my .js code, however, I am not concerned about that because I can't add that until I fix this issue first.

For now, I am just hard coding in a query, "sports", into my function to see if I can get it to fetch articles with that custom query. However, the website displays zero articles and I receive this error message in the console:

Uncaught (in promise) TypeError: response.articles is not iterable at fetchNews (script.js:22:27)

Here is my JavaScript code:

const fetchNews = async (page, q)=>{
console.log(`Fetching news for ${q}, Page number ${page}...`);
var url = 'https://newsapi.org/v2/everything?' +
      'q=' +q+
      '&from=2023-08-02&' +
      'pageSize = 20&' +
      'language=en&'
      'page=' +page+
      '&sortBy=popularity&' +
      'apiKey=1fcf667ddcf54e5db3bb887e60be09a6';

var req = new Request(url);
    
let a = await fetch(req)
let response = await a.json()
console.log(JSON.stringify(response))
    console.log("response")
let str = ""
resultCount.innerHTML = response.totalResults

for (let item of response.articles){
    str = str + `<div class="card my-4 mx-2" style="width: 18rem;">
        <img src="${item.urlToImage}" class="card-img-top" alt="...">
        <div class="card-body">
            <h5 class="card-title">${item.title}</h5>
            <p class="card-text">${item.description}</p>
            <a href="${item.url}" target="_blank" class="btn btn-primary">Go somewhere</a>
        </div>
        </div>`
    }
    document.querySelector(".content").innerHTML = str
search.addEventListener("click", (e)=>{
e.preventDefault()
let query = searchInput.value
fetchNews(1, query)
})
}
    
fetchNews(1, "sports")

And here is my HTML code:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>News App</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
  </head>
  <body>
    <nav class="navbar navbar-expand-lg bg-body-tertiary">
        <div class="container-fluid">
          <a class="navbar-brand" href="#">TechX</a>
          <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto mb-2 mb-lg-0">
              <li class="nav-item">
                <a class="nav-link active" aria-current="page" href="#">Home</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
              </li>
              <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                  News
                </a>
                <ul class="dropdown-menu">
                  <li><a class="dropdown-item" href="#">A.I.</a></li>
                  <li><a class="dropdown-item" href="#">Finance</a></li>
                  <li><hr class="dropdown-divider"></li>
                  <li><a class="dropdown-item" href="#">New Stuff</a></li>
                </ul>
              </li>
            </ul>
            <form class="d-flex" role="search">
              <input id="searchInput" class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
              <button id="search" class="btn btn-outline-success" type="submit">Search</button>
            </form>
          </div>
        </div>
      </nav>
    <div class="container">
        <h1>Summary of the Hottest News Here! (<span id="resultCount"></span> Results)</h1>
        <div class="row content">
          
          <div class="card my-4 mx-2" style="width: 18rem;">
            <img src="..." class="card-img-top" alt="...">
            <div class="card-body">
              <h5 class="card-title">Card title</h5>
              <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
              <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
          </div>
        </div>
      </div>
      <div class="d-flex justify-content-around">
      <button class="btn btn-primary">Previous Page</button>
      <button class="btn btn-primary">Next Page></button>
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" 
        integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm" 
        crossorigin="anonymous"></script>


        <script src="script.js"></script>

</body>

</html>

Earlier I tested out fetching the recent news by hard coding the raw HTTP of a certain search as my 'response' variable, and that works. But I am not sure why this is not working.

0

There are 0 best solutions below