SnaccOvenFlour
SnaccOvenFlour

Reputation: 156

The response from API is undefined

So I'm attempting to make an authentication system using tokens. This works via sending a get request with a token in it and the API is supposed to give information back. I'm encountering an error which is TypeError: Cannot read property 'Error' of undefined and the error is pointing to this line if (UserData.Error == "Token not valid") {return false}. So I'm guessing this means the response of API is not getting put into UserData. The API works fine and here is the response if the token is right:

{
    "username": "admin",
    "is_staff": true,
    "email": "[email protected]"
}

Here is the response when token is not right

{
    "Error": "Token not valid"
}

Here is my code:

function isAuthenticated() {
    const authtoken = localStorage.getItem('AuthToken')
    if (authtoken == null) {
        return false
    } else {
        let UserData;
        axios.get(`http://localhost:8000/api/token/?token=${authtoken}`).then(function(request) {
            UserData = request.data
        })
        if (UserData.Error == "Token not valid") {return false}
        else {return UserData}
    }
}

Upvotes: 1

Views: 866

Answers (1)

Kumar KS
Kumar KS

Reputation: 953

Since ajax request will work in asynchronous manner in js, we can make the call as synchrous with async await.

async function isAuthenticated() {
    const authtoken = localStorage.getItem('AuthToken')
    if (authtoken == null) {
        return false
    } else {
        let UserData;
        UserData = await axios.get(`http://localhost:8000/api/token/?token=${authtoken}`).then(function(request) {
          return request.data
        })
        if (UserData.Error == "Token not valid") {return false}
        else {return UserData}
    }
}

# while executing use await
userData = await isAuthenticated()

Upvotes: 1

Related Questions