Search code examples
javascriptjqueryjsonxmlhttprequesttwitch

HTTP GET/POST Request with Twitch API and JSON.parse


So first I'm new to ajax and JSON http get request, etc. I try to use the new Twitch API to get information about streamers.

var token = $.ajax({
   'url' : 'https://api.twitch.tv/kraken/oauth2/token?client_id=XXX&client_secret=XXX&grant_type=client_credentials',
   'type' : 'POST',
   'success' : function(data) {
     console.log(data.access_token);
     localStorage.setItem('token', data.access_token)
   }
});

var test = $.ajax({
    headers: {'Authorization': 'Bearer ' + localStorage.getItem('token')},
    'url' : 'https://api.twitch.tv/helix/users?login=nightbot',
    'type' : 'GET',
    'success' : function(data) {
      console.log(data); // returns an obj with an data array, length 1
      console.log(data[0]); // undefined
      console.log(data.display_name); // undefined
      console.log(JSON.parse(data)); // syntax error
      console.log(JSON.parse(data[0])); // syntax error
      //$( "#result" ).load( data.display_name ) //to do
    }
});

DATA: https://i.sstatic.net/JcXaE.png

I think that this way is a bit messed up. Is is?

My second problem is, that I can't access the data from the GET REQUEST. The output shows me that there is data but somehow I can't access it and I don't know why.


Solution

  • The output shows me that there is data but somehow I can't access it and I don't know why

    As per the OP statement :

    console.log(data); // returns an obj with an data array, length 1
    

    Hence, to access the array first element you should use below statement.

    console.log(data.data[0]);