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

208
Views
¿Cómo devolver el código de estado de la API obtenido y la respuesta al siguiente paso en JavaScript?

Estoy usando una API que devuelve el código HTTP correcto y un mensaje relacionado con ese código de estado como resultado. Podría encontrar esta solución en StackOverflow:

 fetch(`${baseUrl}api/user/login`, { credentials: "include", // ¹ See note below headers: myHeaders }) .then(function(response) { console.log(response.status); // Will show you the status if (!response.ok) { throw new Error("HTTP status " + response.status); } return response.json(); }) .then(// ... I need status code and error message here

pero para este caso, debo usar response.json() para obtener el mensaje de error. Entonces, necesito un truco para devolver los datos json y el código de estado al siguiente paso y luego manejar la alerta de mensaje.

Quiero decir, no hay ningún mensaje la primera vez y no tengo acceso al código de estado en el siguiente paso para manejar el color del cuadro de alerta.

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

0

La forma rápida y sucia es anidar then llamar.

 return response.json().then(parsed_json => [response.status, parsed_json])

La forma más clara es reescribir su código para usar await para que todas las variables permanezcan en el alcance y no necesite devolverlas explícitamente.

 const response = await fetch(`${baseUrl}api/user/login`, { credentials: "include", // ¹ See note below headers: myHeaders }); console.log(response.status); // Will show you the status if (!response.ok) { throw new Error("HTTP status " + response.status); } const parsed_json = await response.json(); console.log(parsed_json, response.status);
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!