【问题标题】:JS fetch() and jQuery $.ajax returning different responseJS fetch() 和 jQuery $.ajax 返回不同的响应
【发布时间】:2021-10-27 05:27:43
【问题描述】:

我对这个 JS async/await 函数有点陌生,我想知道为什么它似乎返回与 jQuery $.ajax() 函数不同的数据。

我在 Python/Django 环境中开发,这是我发送 JSON 响应的视图

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)

这是我用于异步获取数据的 JS。 (我将两者结合起来只是为了同时记录两个输出)

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);
    }
});

下面是输出

Ajax 调用输出:

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

异步/等待输出:

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

见下图:

问题不在于将 jquery ajax 转换为 JS fetch(),而在于两个函数的响应不同。所选答案准确地回答了问题。 jquery ajax转JS fetch(),参考How to convert Ajax to Fetch API in JavaScript?

【问题讨论】:

  • async 函数总是返回 Promise
  • 您的示例不做同样的事情。 fetch() 部分必须是 get_jwt_token().then(response => response.json() /*or .text()*/).then(token => console.log(token))
  • 你对fetch结果的比较相当于return $.ajax而不是完整的ajax结果
  • 我更新了你的标题,相关问题可以在这里找到。 stackoverflow.com/q/46803768/14032355
  • 这能回答你的问题吗? How to convert Ajax to Fetch API in JavaScript?

标签: javascript jquery ajax async-await django-views


【解决方案1】:

在您的 get_jwt_token() 函数中,您需要返回 token.json()。

来自https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch的解释

fetch() 不直接返回 JSON 响应正文,而是返回一个使用 Response 对象解析的 Promise。

反过来,Response 对象并不直接包含实际的 JSON 响应主体,而是代表整个 HTTP 响应。因此,为了从 Response 对象中提取 JSON 正文内容,我们使用 json() 方法,该方法返回第二个 Promise,该 Promise 解析为将响应正文文本解析为 JSON 的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 2021-10-06
    • 2011-05-12
    • 1970-01-01
    • 2021-08-24
    • 2011-03-09
    • 2014-10-24
    相关资源
    最近更新 更多