Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

340
Vistas
Javascript Fetch Requesting API Token through Body

I am trying to build a frontend using Javascript Fetch to communicate with an API service.

I have to generate a token using the POST method sending apiKey parameter in the Body, and then I have to use the token generated and send it in another POST including date parameters: FechaInicio (StartDate), FechaFinal (currentDate) to retrieve data.

This is how it looks in Postman (Requesting Token):

enter image description here

Requesting Data (Sending token): enter image description here

This is what I have so far:

        <div>
        <table>
            <thead>
                <tr>
                    <th>numeroConsecutivo</th>
                    <th>condicionVenta</th>
                </tr>
            </thead>
            <tbody id="data">
            </tbody>
        </table>
    </div>
    <script>
        let url = 'https://www.fakeurl.com/webservices/bills.php';//fake
        const apiKey = '+%a4Ur734687631';///fake
        const fechaInicio = "19990101"; //Initial Date
        var fechaFinal = new Date(); //Get current Date, format: 20220416
        var dd = String(fechaFinal.getDate()).padStart(2, '0');
        var mm = String(fechaFinal.getMonth() + 1).padStart(2, '0'); //January is 0!
        var yyyy = fechaFinal.getFullYear();
        fechaFinal = yyyy + mm + dd; 

        fetch(url),{
            method: 'POST',
            body: {
                'apiKey': (apiKey) 
            }
            
        .then(response => response.json())//Get Token
        .then(token => displayToken(token))
        .catch(error => console.log(error))
        },

        fetch(url),{
            method: 'POST',
            body: {
                'token': (token), 
                'fechaInicio': (fechaInicio),
                'fechaFinal': (fechaFinal) 
            }
            
            .then(response => response.json())
            .then(data => displayData(data))
            .catch(error => console.log(error)),

            const displayData = (data) => {
            console.log(data)
            let body = ""
            for (var i = 0; i < data.length; i++) {
                body += `<tr><td>${data[i].numeroConsecutivo}</td><td>${data[i].condicionVenta}</td></tr>`
            }
            document.getElementById('data').innerHTML = body
            //console.log(body)
            }
        }       
    </script>

Any help will be really appreciated!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Since your second fetch request depends on the first one, it is better to chain the request - make the second request only after getting the response for the first request.

Then on the success of the second request, we modify the DOM. We can also use callbacks, but this is more readable.

<div>
  <table>
    <thead>
      <tr>
        <th>numeroConsecutivo</th>
        <th>condicionVenta</th>
      </tr>
    </thead>
    <tbody id="data"></tbody>
  </table>
</div>
<script>
  let url = 'https://www.fakeurl.com/webservices/bills.php' //fake
  const apiKey = '+%a4Ur734687631' ///fake
  const fechaInicio = '19990101' //Initial Date
  var fechaFinal = new Date() //Get current Date, format: 20220416
  var dd = String(fechaFinal.getDate()).padStart(2, '0')
  var mm = String(fechaFinal.getMonth() + 1).padStart(2, '0') //January is 0!
  var yyyy = fechaFinal.getFullYear()
  fechaFinal = yyyy + mm + dd
  const displayData = (data) => {
    console.log(data)
    let body = ''
    for (var i = 0; i < data.length; i++) {
      body += `<tr><td>${data[i].numeroConsecutivo}</td><td>${data[i].condicionVenta}</td></tr>`
    }
    document.getElementById('data').innerHTML = body
    //console.log(body)
  }

  fetch(url, {
    method: 'POST',
    body: {
      apiKey: apiKey,
    },
  })
    .then((response) => response.json()) //Get Token
    .then((token) => {
      displayToken(token)
      return fetch(url, {
        method: 'POST',
        body: {
          token: token,
          fechaInicio: fechaInicio,
          fechaFinal: fechaFinal,
        },
      })
    })
    .then((response) => response.json())
    .then(displayData)
    .catch((error) => console.log(error))
</script>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda