When I send a route.get request from the serve it responds with JSON data successfully and displays on localhost:/view/product page, however, I want it to process my client side html page and display the database info into the table there. It is not doing that.
My goal is to GET this data and display it into a simple html table on the localhost:3000/view/product route.
Any advice would be appreciated, thank you in advance.
My html table attempt:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="app.css">
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css">
<div>
<header>
<h2><a href="/"><i></i> VIEW PRODUCTS </a></h2>
</header>
</div>
</head>
<body>
<div id="table">
<table align='center' cellspacing=2 cellpadding=5 id="productTable" border=1>
<thead>
<th> Product Name </th>
<th> Quantity </th>
<th> Price </th>
</thead>
<tbody id="productTable"></tbody>
</table>
</div>
</body>
</html>
<script>
$.get('/view/product', {}, function(results) {
let res = '';
results.forEach(data => {
res = `<tr><td>${data.productname}</td><td>${data.quantity}</td><td>${data.price}</td></tr>`
})
$('#place-here').html(res)
});
</script>
my get request:
route.get("/view/product", async function (req, res) {
try {
const results = await db.query("SELECT * FROM product ORDER BY createdAt DESC;",
);
// console.log(results);
// res.status(200).json({
// status: "success",
// results: results.rows.length,
// data: {
// orders: results.rows,
// },
// });
} catch (err) {
console.log(err);
}
});
loading the html page in my index.js file:
app.get('/view/product',function(req,res){
res.sendFile('view.html', { root: __dirname });
});
CodePudding user response:
You can't use the same path for both your page load and for the Ajax call to fetch JSON as they are both GET routes so only the first one registered with your Express server will ever get a chance to see the incoming request.
I'd suggest you change the Ajax call to something like /api/products and then change the corresponding definition on your server for the route that returns JSON.
