如果您想向客户端发送 html 响应而不是 JSON 响应,您可以使用 HTML 模板引擎。
让我给你看一个Handlebars.js的例子
第 1 步:运行npm install --save handlebars
第 2 步:在项目的根目录中创建一个文件 cars.hbs
第 3 步:在您的 cars.hbs 文件中添加以下代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cars</title>
<style>
html {
padding: 0;
margin: 0;
}
body {
position: relative;
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
width: 100%;
margin: 0;
}
</style>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Year</th>
<th>Engine Size</th>
<th>Accelaration</th>
<th>Top Speed</th>
<th>Consumption</th>
<th>Image</th>
</tr>
{{#each cars}}
<tr>
<td>{{this.name}}</td>
<td>{{this.enginesize}}</td>
<td>{{this.maxpower}}</td>
<td>{{this.accelaration}}</td>
<td>{{this.topspeed}}</td>
<td>{{this.consumption}}</td>
</tr>
{{/each}}
</table>
</body>
</html>
第 4 步:在您的 js 文件(包含 get/cars api)中添加以下代码
const handlebars = require("handlebars");
const fs = require("fs");
app.get("/get-cars", function (req, res) {
let sql = "SELECT * FROM cars";
let query = db.query(sql, (err, results) => {
if(err) throw err;
const data = { cars: result };
const template = fs.readFileSync("./cars.hbs", "utf8");
const html = handlebars.compile(template)(data);
res.send(html);
});
});
第 5 步:打开浏览器并访问 http://localhost:3000/get-cars
或者,您可以从前端调用 API,并使用您选择的格式在浏览器中显示数据。