Requesting an API token through the body using Javascript's Fetch function

I'm currently working on developing a frontend application using Javascript Fetch to interact with an API service.

One of the tasks I need to accomplish is to create a token by using the POST method and sending an apiKey parameter in the Body. Once I have the token, I then need to make another POST request with the token along with date parameters: StartDate and currentDate to fetch some data.

Here's how it appears in Postman (Token Request):

https://i.stack.imgur.com/npNuu.png

Data Request (Sending token): https://i.stack.imgur.com/wIbq0.png

This is my progress 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 assistance or suggestions would be greatly appreciated!

Answer №1

To ensure the second fetch request is dependent on the first one, it's best to chain the requests - wait for the response of the first request before making the second one.

Upon success of the second request, we can then modify the DOM. Although callbacks are an option, chaining requests makes the code more readable and organized.

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance the list visualization in Next.js by efficiently transferring data from child components

In my Next.js Page component, I have a setup similar to the following: export default function Index({ containers }) { const [containerListState, setContainerListState] = useState(containers); const updateContainerList = (container) => { contai ...

Retrieve the earliest and latest dates from a JSON file to utilize with FlatPicker

I have a file in an unknown format, possibly JSON, with dates listed. I am attempting to extract the minimum and maximum dates from this data in MM/DD/YYYY format for use as variables in Flatpicker's minDate and maxDate options. The current AJAX call ...

Show XML data with namespaces - utilizing PHP

Can someone help me figure out how to display values from an API that returns XML? I've been searching, but most examples don't have namespaces or handle both. When I try with both, it always causes bugs and fails to display the values... Here i ...

Point the direction to nextjs and react native expo web

I am currently working on redirecting a URL to another within my website, specifically in Next.js and Expo React Native Web. While I don't have an actual "About" page, I do have other pages nested under the "about" folder and am aiming to direct any ...

Displaying a div when a radio button is clicked in React

I am attempting to create a functionality where clicking on one radio button will display another div in React. As a beginner in React, I have tried implementing the code below but encountered issues with hiding and displaying the content based on user inp ...

Is it appropriate for HTML5 Web Workers to utilize CORS for cross-origin requests?

As I was creating a hosted API that relies on web workers, I encountered an intriguing issue. I am looking for feedback from the community to help me with this. Even though my server has the necessary CORS headers in place to serve the worker JS files and ...

Is there a workaround for the issue of the NodeJS Web Cryptography API require() being undefined in an unsecure origin (Heroku App)?

My goal is to implement the experimental Web cryptography API (SubtleCrypto) on my Node.js server hosted on Herokuapp. The aim is to encrypt data from a fetch request sent from gitpages to herokuapp, concealing sensitive information from the browser consol ...

Guide to toggling the anchor tag functionality as a button with JavaScript

I am trying to dynamically enable or disable an anchor tag that is used as a button using JavaScript. Within a certain condition, I want to control the state of this button. Here is the specific button in question: <div class="row my-2 text-right& ...

Executing jQuery script on dynamically loaded content

My website utilizes AJAX requests to load pages dynamically. One specific page includes a marquee script that I would like to implement. Unfortunately, due to the dynamic loading of the page, the marquee script is not functioning as expected. I have come ...

Inserting a border both above and below an element may result in the parent overflowing

I am facing an issue similar to the following: div.parent { height: 100px; padding: 20px; box-sizing: border-box; overflow: auto; } div.parent div.thing { height: 20px; width: 90%; border: 1px solid black; } <div class="parent"> ...

Every time I attempt to load the table, I encounter an error

Encountering errors when attempting to load the table: 'Uncaught ReferenceError: usersArray is not defined at loadUsers (trgames.js:20:17) at trgames.js:22:1' and 'Uncaught TypeError: Cannot set properties of null (setting ...

Deactivate button using Javascript

Can anyone assist me with this issue I am having? I currently have a button set up as follows: <input type="button" id="myButton" name="myButton" value="ClickMe!!" onClick="callMe()"/> I need to disable the button using jQuery, standard javascript ...

The AJAX request encountered an unexpected failure that cannot be identified (Using jQuery)

Are you facing issues with a service that returns JSON data? Check out this URL: If you're attempting a simple AJAX request, here's some sample code to get you started: $.ajax({ type: "get", url: "http://api.drag2droid.shamanland.com/ca ...

Execute function upon initial user interaction (click for desktop users / tap for mobile users) with the Document Object Model (DOM)

Looking to trigger a function only on the initial interaction with the DOM. Are there any vanilla JavaScript options available? I've brainstormed this approach. Is it on track? window.addEventListener("click", function onFirstTouch() { console.l ...

Displaying postcode on a category page: A step-by-step guide

I would like to showcase the user input code and present it on the web exactly as entered. <?php #code... ?> Any assistance is greatly appreciated. Please excuse my English. Thank you! ...

Breaking down the jQuery datepicker into individual fields for Day, Month, and Year

Currently, I am using the Contact Form 7 plugin on my Wordpress website, which I believe uses the jQuery datepicker for its date fields (please correct me if I'm mistaken). My query is about splitting the user input box into three separate elements ( ...

How can I obtain an array using onClick action?

Can anyone help me figure out why my array onClick results are always undefined? Please let me know if the explanation is unclear and I will make necessary adjustments. Thank you! Here is the code snippet: const chartType = ["Line", "Bar", "Pie", " ...

Discovering the method for accessing a variable within jQuery from a regular JavaScript function

As someone new to jQuery, I am currently facing a challenge with accessing a variable defined inside a jQuery block from a regular function. Despite my attempts, I have been unsuccessful in accessing it. Can anyone guide me on how to do this? <script l ...

HTML/CSS - Enhances user experience by zooming in on select tag when tapped on mobile devices

I am experiencing an issue with a select menu on mobile devices. Whenever I tap on the menu, it seems to zoom in slightly. Is there a particular -webkit property causing this behavior? How can I prevent the screen from zooming when I tap on the select me ...

What is the process of incorporating a video into a react.js project through the use of the HTML

I'm experiencing an issue where my video player loads, but the video itself does not. Can anyone shed light on why this might be happening? class App extends Component { render() { return ( <div className="App& ...