1

Im somewhat new to this JS async/await functions and im wondering why does it seem to return a different data compared to the jQuery $.ajax() function.

Im developing in Python/Django environment and here is my view which is sending the JSON response

class GetUserToken(APIView):
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request, format=None):
        refresh = RefreshToken.for_user(request.user)
        content = {
            'user': str(request.user),  # `django.contrib.auth.User` instance.
            'access': str(refresh.access_token),
            'refresh': str(refresh),
        }
        return Response(content)

Here is my JS for getting the data asynchronously. (I combined both just so I can log both output at the same time)

async function get_jwt_token(){
    const token = await fetch('/api/user/token/');
    return token;
}

$.ajax({
    url: '/api/user/token/',
    method: 'GET',
    success: function(data){
        console.log(data);
        get_jwt_token().then(function(result){
            console.log(result);
        }).catch((e) => console.log(e));
    },
    error: function(xhr, status, err){
        console.log(err);
    }
});

below is the output

Ajax call output:

{
"user": "admin",
"access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjMwMDc0ODg5LCJqdGkiOiI5NDAzZjBmMjI0MDU0NzFhODYwYmE4ZGIzNWUwYmI5NyIsInVzZXJfaWQiOjF9.Ee86WDrbiV4Oj2-MyWc3vSIZ5ly2vgbbJflErv-6aN0",
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYzMDEzOTY4OSwianRpIjoiYzVjMjU4ZjM2YzZmNGIxY2FlOGRhODkyZWRhYmRjNDIiLCJ1c2VyX2lkIjoxfQ.sO3e4_6QoidFD5Z6edIrDJidFrKpqFvRt1jljsOL22Q"
}

Async/Await output:

{
  type: "basic",
  url: "http://localhost:8000/api/user/token/",
  redirected: false,
  status: 200,
  ok: true,
   …
}

See image below:

enter image description here

The question is not about converting jquery ajax to JS fetch(), it's about the difference in the response of both function. The selected answer precisely answered the question. For converting jquery ajax to JS fetch(), refer to How to convert Ajax to Fetch API in JavaScript?

JCm
  • 1,919
  • 8
  • 27
  • 42
  • 1
    `async` functions always return a `Promise` – Andreas Aug 27 '21 at 08:52
  • 2
    Your examples don't do the same thing. The `fetch()` part would have to be `get_jwt_token().then(response => response.json() /*or .text()*/).then(token => console.log(token))` – Andreas Aug 27 '21 at 08:53
  • Your comparison of the `fetch` result is the equivalent of `return $.ajax` rather than the completed ajax result – freedomn-m Aug 27 '21 at 08:55
  • 2
    I updated your title, and the related question can be found here. https://stackoverflow.com/q/46803768/14032355 – ikhvjs Aug 27 '21 at 09:15
  • Does this answer your question? [How to convert Ajax to Fetch API in JavaScript?](https://stackoverflow.com/questions/46803768/how-to-convert-ajax-to-fetch-api-in-javascript) – freedomn-m Aug 27 '21 at 10:40
  • They are related, but not the exact question. @freedomn-m – JCm Aug 27 '21 at 10:49

1 Answers1

2

In your get_jwt_token() function you need to return token.json().

Explanation from https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch() does not directly return the JSON response body but instead returns a promise that resolves with a Response object.

The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON.