【发布时间】: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
标签: javascript jquery ajax async-await django-views