Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

338
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda