这是一个简单的设置:
1) Express 从执行 client.js 的 public/ 文件夹中提供 index.html
2) 我们有一个 Express 路由,它读取 template.json 文件并将其加载到 /json/ 的路由中
3) client.js 通过 fetch() 执行 Ajax 请求,命中 /json/ 路由,该路由将 JSON 内容提供给浏览器脚本
index.js
const express = require("express");
const app = express();
const data = require("./template.json");
app.use( express.static( __dirname + '/public' ) );
app.get("/json", (req,res)=>{
// Send a JSON response with the data from template.json
res.json( data );
})
app.listen( 8080 );
index.html
<!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>Express</title>
</head>
<body>
<h1>Express</h1>
<script src="client.js"></script>
</body>
</html>
client.js
// Make an HTTP request to the /json/ route of our express server:
fetch("/json")
// Get the request body and convert to JSON:
.then((res)=> res.json())
// Here we have the request body as a JSON object ready to be used:
.then((data)=>{
console.log( data );
})
.catch(console.error);
template.json
{"firstname":"john","lastname":"doe"}
参考资料: