1. 后端代码
1.1 创建一个 server.js
文件:
javascript
const express = require("express");
const fs = require("fs");
const path = require("path");
const app = express();
const PORT = 3000;
// 为了解决跨域问题,添加 CORS 头
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
// 提供 JSON 数据
app.get("/api/data", (req, res) => {
const dataPath = path.join(__dirname, "data.json");
fs.readFile(dataPath, "utf-8", (err, data) => {
if (err) {
res.status(500).send("Internal Server Error");
return;
}
res.setHeader("Content-Type", "application/json");
res.send(data);
});
});
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
1.2 创建 data.json
文件:
json
{
"weather": {
"location": {
"name": "San Francisco",
"country": "USA"
},
"current": {
"temp_c": 15,
"condition": {
"text": "Partly cloudy"
}
}
},
"map": {
"formatted_address": "San Francisco, CA, USA"
}
}
1.3 启动服务:
sh
node server.js
2. 前端代码
2.1 创建一个 index.html
文件:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Weather App</title>
</head>
<body>
<div id="app">
<input
type="text"
id="city"
placeholder="Enter city name"
value="San Francisco"
/>
<button id="searchBtn">Search</button>
<div id="weatherContainer"></div>
</div>
<script src="app.js"></script>
</body>
</html>
2.2 创建一个 app.js
文件:
javascript
document.getElementById("searchBtn").addEventListener("click", function () {
let city = document.getElementById("city").value;
fetch(`http://localhost:3000/api/data`)
.then((response) => response.json())
.then((data) => displayData(data, city))
.catch((error) => console.error("Error:", error));
});
function displayData(data, city) {
if (data.weather.location.name.toLowerCase() !== city.toLowerCase()) {
alert("City not found!");
return;
}
let container = document.getElementById("weatherContainer");
container.innerHTML = `
<h2>${data.weather.location.name}, ${data.weather.location.country}</h2>
<p>Temperature: ${data.weather.current.temp_c} °C</p>
<p>Condition: ${data.weather.current.condition.text}</p>
<p>Address: ${data.map.formatted_address}</p>
`;
}
在此代码中,前端会向后端的 /api/data
端点发送请求,然后将返回的 JSON 数据展示在页面上。由于这里是示例代码,只用了一个静态的 JSON 文件,并且前端也仅根据输入的城市名称来显示相关的 JSON 数据。在真实的应用中,你可能会根据用户的输入动态地构建 URL,从而向服务器请求相关的数据。