Twitchtv challenge - Help needed

Hi All,

I am a beginner to programming and for a challenge I need to get the status (Streaming live/Off-line) for a given number of channels.

I wrote an ajax request but I am still getting 401 as a response. Below my code and a screen shot of the response.

$("document").ready(function() {

var aoathToken = $.ajax({
    type: "POST",
    url: "https://id.twitch.tv/oauth2/token?client_id=MYCLIENTID&client_secret=MYSECRET&grant_type=client_credentials",
    error: function() {
        console.log("Check your request!!")
    },

    success: function(token) {
        console.log(token);
    }
})

$.ajax({
    type: "GET",
    url: "https://api.twitch.tv/helix/streams?user_id=freecodecamp",
    contentType: ('application/x-www-form-urlencoded; charset=UTF-8'),
    crossDomain: true,
    header: {
        "Access-Control-Allow-Origin": "*",
        "Client-ID": "MY CLIENT ID",
        "Authorization": "Bearer " + aoathToken,
    },
    data: {"user_login": "myUserID"},
    dataType: "json",
    success: function(json) {
        console.log(JSON.stringify(json, null, 2));
    },
    error: function(json) {
        window.alert(json.status + " " + json.message);
    },
})

});

image

thanks in advance

$.ajax is asynchronous. Your second call to helix/streams fires before the aoathToken one has finished. $.ajax also doesn’t return its results, but passes them to the callback (your success function, which you correctly do have there).

1 Like

Hi,

Thanks for your response. Just for the sake of testing, I set the aoathToken request to async: false so I am sure that my token is back before triggering the sencond request. But I am still getting the same response :frowning:

Don’t know what I else I can do.

The calls are asynchronous so that they do not block UI updates and the page stays responsive to the user.

What you should do instead of disabling async is use the callback function to fire the additional request, along the lines of:

// -snip-
    success: function(token) {
        console.log(token);
        // token will be something along the lines of
        // "{\"access_token\":\"sometoken\",\"refresh_token\":\"\",\"expires_in":3600,\"scope\":[]}"
        // parse the json string in token, see JSON.parse()
        // call getStream with the parsedData.access_token
    }
})

function getStream(token) {
    $.ajax({
        type: "GET",
        url: "https://api.twitch.tv/helix/streams?user_id=freecodecamp",
        // -snip-
    })
}

This way your second ajax will be called after the first one has successfully returned without negative user experience from blocking synchronous requests.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.