0

Error:

Cannot read properties of undefined (reading 'name')

Code:

function loop(){
    request.get({
        url: 'https://games.roblox.com/v1/games?universeIds=3652651589',
        rejectUnauthorized: false,
        headers: {
          'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3750.0 Iron Safari/537.36'
        }
      }, (err, res, body) => {
        console.log(body.data.name)
      });

    setTimeout(loop, 5000);
}

loop();

What must I do?

Ivar
  • 6,138
  • 12
  • 49
  • 61
poorguy
  • 1
  • 1
  • 1
  • 1
  • 1
    Sounds like name isnt on body.data. Try printing just body.data, to determine how to get what you want. – matttm Jun 22 '22 at 12:32
  • output: undefined – poorguy Jun 22 '22 at 12:33
  • It means that body.data doesn't have property named "name", try to log "body" and "body.name" to debug – nem0z Jun 22 '22 at 12:34
  • when i use just 'body' this time it gives all the data but I want to use only certain data like 'playing' – poorguy Jun 22 '22 at 12:37
  • still undefined :/ – poorguy Jun 22 '22 at 12:41
  • The `data` property in the JSON that is returned by that endpoint, is an array. An array doesn't have a `name` property. You will have to loop over the elements in `.data`. See [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Ivar Jun 22 '22 at 12:45
  • since you keep getting undefined, log the error in your callback, theres might be an error in the req then. instead of calling setTimeout in loop, why not use setInterval from outside of it – matttm Jun 23 '22 at 12:37

2 Answers2

1

data is an array, you can not do things like that data.name
You need to use some array methods to access the information in the data or simply to specify exact index in the array in this case is 0 because the data array has only one item in it, but this is kind of not scalable...

body.data.map((currentElement) => { console.log(currentElement.name) }
and "On Development" should be printed.

Dobromir Kirov
  • 934
  • 4
  • 16
-3

Replace body.data.name with res.data.name

Nitin Ramnani
  • 314
  • 1
  • 7
  • same error. thats the body data ```{"data":[{"id":3652651589,"rootPlaceId":9890477108,"name":"On Development","description":"","sourceName":"On Development","sourceDescription":"","creator":{"id":13708790,"name":"Schrater Studios","type":"Group","isRNVAccount":false},"price":null,"allowedGearGenres":["All"],"allowedGearCategories":[],"isGenreEnforced":true,"copyingAllowed":false,"playing":0,"visits":15,"maxPlayers":6,"created":"2022-06-12T13:56:48.163Z","updated":"2022-06-22T12:27:40.9492273Z","studioAccessToApisAllowed":false,"createVipServersAllowed":false,....}]}``` – poorguy Jun 22 '22 at 12:39