Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
JS fetch() y jQuery $.ajax devolviendo una respuesta diferente

Soy algo nuevo en estas funciones JS async/await y me pregunto por qué parece devolver datos diferentes en comparación con la función jQuery $.ajax().

Estoy desarrollando en el entorno Python/Django y aquí está mi vista que envía la respuesta 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)

Aquí está mi JS para obtener los datos de forma asíncrona. (Combiné ambos solo para poder registrar ambos resultados al mismo tiempo)

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

a continuación se muestra la salida

Salida de llamada Ajax:

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

Salida asíncrona/en espera:

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

Ver imagen a continuación:

ingrese la descripción de la imagen aquí

La pregunta no se trata de convertir jquery ajax a JS fetch(), se trata de la diferencia en la respuesta de ambas funciones. La respuesta seleccionada respondió con precisión a la pregunta. Para convertir jquery ajax a JS fetch(), consulte ¿Cómo convertir Ajax a Fetch API en JavaScript?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

En su función get_jwt_token() necesita devolver token.json().

Explicación de https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch() no devuelve directamente el cuerpo de la respuesta JSON, sino que devuelve una promesa que se resuelve con un objeto de respuesta.

El objeto Response, a su vez, no contiene directamente el cuerpo de la respuesta JSON real, sino que es una representación de la respuesta HTTP completa. Entonces, para extraer el contenido del cuerpo JSON del objeto Respuesta, usamos el método json(), que devuelve una segunda promesa que se resuelve con el resultado de analizar el texto del cuerpo de la respuesta como JSON.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!