Retrieve a list of items using the GET method when the button is clicked, then display them in an HTML table on

Accessing the GET method to retrieve a list of cars:

const express = require('express')

const app = express()

app.use(express.static('public'))

app.get('/cars', (req, res) => {
    res.status(200).json([{
        name :  'a',
        color : 'red'
    },{
        name :  'b',
        color : 'blue'
    }])
})

module.exports = app

My goal is to display this list in my HTML page:

By clicking on the button with the load id, it triggers a request for the list of cars with red color from the server. The cars are then loaded into a table with the main id, each car occupying its own tr element.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>A simple app</title>
    <script>
    async function load(){
try{
     let url ='http://localhost:8080/cars'
       let response = await fetch(url)
        let data = await response.json()
        let table = document.getElementById('main')
         table.innerHTML = ''
            for (let e of data){
                 let rowContent = `
                    <tr>
                            <td>
                                ${e.name}
                            </td>
                            <td>
                                ${e.color}
                            </td>
                        </tr>`
                    let row = document.createElement('tr')
                    row.innerHTML = rowContent
                    //row.dataset.id = e.id
                    table.append(row)
            }
              catch(err){
                    console.warn(err)
                }

}
    }
    </script>
</head>
<body>
    A simple app
    <table id=main></table>
    <input type="button" value="add" onClick={load()} id="load"/>
</body>
</html>

Answer №1

There may be a few obstacles preventing you from achieving this, such as the use of cors, catch block, and port.

You could attempt implementing the following html code:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>A simple app</title>
    <script>
    async function load(){

        try {
            let url ='http://localhost:3000/cars';
            let response = await fetch(url);
            let data = await response.json()
            let table = document.getElementById('main');
            table.innerHTML = '';
            for (let e of data){
                let rowContent = `
                    <tr>
                        <td>${e.name}</td>
                        <td>${e.color}</td>
                    </tr>`;
                let row = document.createElement('tr')
                row.innerHTML = rowContent;
                table.append(row);
            }
        } catch(ex) {
            console.log(ex);
        }
    }
    </script>
</head>
<body>
    A simple app
    <table id=main></table>
    <input type="button" value="add" onClick={load()} id="load"/>
</body>
</html>

If necessary, consider configuring your server with the following minimal setup:

const express = require('express');
const app = express();

const cors = require('cors');
app.use(cors( { origin: '*'}));


app.get('/cars', (req, res) => {
  res.status(200).json([{
      name :  'a',
      color : 'red'
  },{
      name :  'b',
      color : 'blue'
  }])
});


app.listen(3000, () => {
  console.log('Server is up');
});

Hope these instructions prove helpful in resolving your issue.

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

Delay the processing of incoming HTTP requests in Node.js

Intentionally maintaining a broad scope here because I have a feeling I might be overlooking a key concept. Working with a Node/Express server, my goal is for the server to serve as a throttle by storing incoming http requests (either in memory or a separ ...

Nginx not returning response headers as expected

After setting up a Nginx reverse proxy on top of a nodejs/express Rest API, the CORS headers are properly configured on the Nodejs rest api. However, when making a curl call directly to this api, the expected response is not received (with Access-Control-A ...

seamless blend of canvas distortion and gradual appearance of particles

Take a look at my work in progress on jsfiddle: https://jsfiddle.net/vzrandom/fkho6grf/8/ I'm experimenting with simplex-noise.js and dat.GUI to add movement to particles. Every 5 seconds, a simulated click occurs on the canvas triggering the start ...

Using Database Data in a Material UI Select Component

I'm having trouble populating a select component from Material UI with data retrieved from my database. Although I can display the data in the component, upon selecting an option it breaks and displays the error "categorias.map is not a function". Any ...

Tips for hiding the overflow scrollbar on Microsoft Chrome when there is no content to scroll

Looking for a solution to hide scroll bars in Microsoft Chrome, but only when there is no content to scroll? The current div and styles always show the horizontal and vertical scroll bars, even when the height exceeds the content. <div style="backgroun ...

One potential solution is sending a message to a user via a server using JavaScript on Node.js

Hey there, I've encountered a minor issue and would appreciate your help. Recently, I developed a weather program in NodeJs where users can search for the weather in their city. However, I'm facing a challenge with displaying the weather data to ...

Ways to maintain an array in Vuex even after mutations take place? (Specifically focusing on persisting data through browser refresh)

I am in the process of developing a basic shopping cart and I need guidance on how to persist an array containing cart data when executing the addProduct mutation below. Is there a way to save this data temporarily to prevent it from being lost due to br ...

What is the best way to change the name of a child object within a clone in three.js? (renaming child objects within clones)

I have designed a 3D model using different elements: ParentObject-001.name = 'ParentObject-001'; ChildObjectA-001.name = 'ChildObjectA-001'; ChildObjectB-001.name = 'ChildObjectB-001'; Then, I combined them with: ParentObject ...

What happens to the code that remains after an "await" promise that will never be resolved?

I have a method that is frequently called and contains several "await" parts with code following them. However, in some cases, these promises may remain unresolved, causing the code after the "awaits" to never be executed. I'm concerned about what hap ...

Choose a particular text node from the element that has been selected

Can anyone provide guidance on how to extract the text "Items Description" from the following HTML snippet using jQuery? <div class="items"> "Items Description" <ul> <li>1. One</li> <li>2. Two</li&g ...

Is there a way to stop Chrome from creating an endless loop while showing alerts during the focus event, without having to disable and enable the event repeatedly?

Looking for a solution to prevent an infinite loop of alert messages in Google Chrome when clicking on cmbMonkeys. The workaround for cmbPeople is working fine, but I'm curious if there's another way to handle alerts on focus or blur events with ...

Having trouble getting the timer function to execute upon page load in JavaScript

My goal is to have my basic timer function activate when the page loads. However, I'm encountering issues with it not working as intended. I suspect there may be an error in the if else loop, possibly here: setTimeout(function(tag, sec), 1000);. How c ...

Display chosen preferences in an Angularjs dropdown alongside additional options

I'm currently developing a blogging software and have implemented an AngularJS dropdown for selecting post terms. Here's the code: <select multiple="multiple" name="terms" ng-model="post.data.attributes.term_ids" required> ...

Ways to dynamically combine a group of objects

I'm grappling with a challenge involving an array containing two objects. After using Promise All to fetch both of these objects, I've hit a roadblock in trying to merge them dynamically. Despite experimenting with various array methods like map, ...

The most basic security measure for safeguarding a webpage

Currently, I am developing a website that requires customers to input a specific "code" in order to gain access. Upon visiting the site, users will be prompted to enter a simple code to proceed further. My programming skills are limited to HTML, CSS, and J ...

How can I locate a single hidden field within a div containing multiple fields?

Within one div, I have three hidden fields. How can I access and retrieve just one of these hidden fields when referencing this specific div? ...

We are experiencing an issue with WebSQL: The number of placeholders in the statement does not match the number of arguments provided

I'm looking to develop a customized function for dynamically inserting data into the webSQL Database. Unfortunately, indexed DB is not an option due to Zetakey's lack of support for it. tx.executeSql("INSERT INTO " + table + "(" + formatfields ...

Comparing Ember.js yield with Sails.js and Handlebars in a Single Page Application (SPA) approach

I am looking to achieve a specific functionality that is typically done in Ember with Handlebars, but I want to accomplish it using only Sails.js and Handlebars. To set up my Sails project, I used the following command: sails new fooProject --template=han ...

What causes inability for JavaScript to access a property?

My current coding project involves the usage of typescript decorators in the following way: function logParameter(target: any, key : string, index : number) { var metadataKey = `__log_${key}_parameters`; console.log(target); console.log(metadataKey ...

The feature of the "pull" and "id" subdocument functions seem to be malfunctioning in Mongoose

I am currently diving into the world of mongoose and nodejs, working on my project while referencing the mongoose documentation. My goal is to remove a specific subdocument in the comment array by identifying it with its id. I have tried using both the "pu ...