Вот простая настройка:
1) Экспресс обслуживает index.html
из папки public/
, которая выполняет client.js
2) У нас есть экспресс-маршрут, который читает template.json
файл и загружает его по маршруту в /json/
3) client.js
выполняет Ajax-запрос через fetch()
, попадает в маршрут /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"}
Ссылки: