documentquerySelector вызывает ошибку (выборка) - PullRequest
0 голосов
/ 30 марта 2020

Я получаю два одинаковых URL-адреса (оба имеют одинаковые конечные точки API), по какой-то причине один из них работает успешно, а другой - (Ошибка загрузки).

Начинающий с javascript и пытается учиться на практике, а Engli sh не мой родной язык, поэтому извините за ошибки.

Этот URL работает

"https://sp*****.com/get/henkilot/98765432/sijoitus", 

, но этот не

"https://sp*****.com/get/henkilot/98765432/". 

Работающий имеет этот json:

[{"Key": "fhd6846d8h","id": "dhdfyj97",},
            {"Key": "fhd6846d8h","id": "dhdfyj97",}],

а тот, который выдает ошибку, имеет json:

 {"id": "9876548","dole": {"Key": "fhd699f"}}

мой код:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <style>

    </style>
</head>
<body>
	<div class="app"></div>

    <script>
 var app = document.querySelector('.app');
          fetch(
            "https://sp*****.com/get/henkilot/98765432/sijoitus",
            {
              method: "GET",
              headers: {
                "x-api-key": "p*****w"
              }
            }
          )
  .then(response => response.json())
  .then(json => {
    app.innerHTML = json.map(x => 
     `<div>
         <h2>${x.id}</h2>
      </div>`
    ).join('');
  })
  .catch(error => {
    console.error('Error loading');
    app.innerHTML = `<h1>Error Loading</h1>`;
  });

    </script>

</body>
</html>

1 Ответ

0 голосов
/ 30 марта 2020

Объект json внутри второго then является простым объектом. Object не имеет карты методов на нем. Если вы хотите перебрать (или go более) каждую запись и выполнить какую-либо операцию, попробуйте методы Object.entries или Object.keys. Одним из способов может быть следующее:

// ... rest of your code
.then(json => {
   if(typeof json === 'object' && json.length) {
       // it's an array of objects
       json.forEach(obj => {
           // now add your code to handle the obj properties
           console.log(obj.id); // print the ID on console
       }
   }
   else if(typeof json === 'object') {
          // it's an object; just handle the object properties
          let temp = json.id; // 
          console.log(temp); // print ID or add to DOM 
          // app.innerHTML = temp;
   }
   else {
           // json is undefined; handle this case as well
   }

})
// ... rest of your code
...