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>