當我從服務器發送 route.get 請求時,它會成功回應 JSON 資料并顯示在 localhost:/view/product 頁面上,但是,我希望它處理我的客戶端 html 頁面并將資料庫資訊顯示到那里的表中。它沒有這樣做。
我的目標是獲取這些資料并將其顯示到 localhost:3000/view/product 路由上的一個簡單的 html 表中。
任何建議將不勝感激,在此先感謝您。
我的 html 表嘗試:
<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>
我的請求:
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);
}
});
在我的 index.js 檔案中加載 html 頁面:
app.get('/view/product',function(req,res){
res.sendFile('view.html', { root: __dirname });
});
uj5u.com熱心網友回復:
您不能對頁面加載和 Ajax 呼叫使用相同的路徑來獲取 JSON,因為它們都是 GET 路由,因此只有在 Express 服務器上注冊的第一個才有機會看到傳入的請求。
我建議您將 Ajax 呼叫更改為類似的/api/products內容,然后更改服務器上回傳 JSON 的路由的相應定義。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/411518.html
標籤:
