3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
```
6. **运行项目**
```bash
node server.js
```
7. **测试项目**
打开浏览器访问 `http://localhost:3000`,你应该能看到动态生成的视频链接。
### 说明
1. **静态资源文件**:`public/index.html` 和 `public/static/stats.js` 分别定义了前端页面结构和JavaScript代码。
2. **后端服务器**:`server.js` 使用Express框架提供了一个简单的API接口来返回比赛信息,并提供了静态资源服务。
3. **项目启动**:通过运行 `node server.js` 启动Node.js服务器。
这样,你就完成了一个完整的前后端结合的NBA比赛信息展示系统。希望这些步骤和示例能帮助你更好地理解和构建类似的应用!如果有任何问题或需要进一步的帮助,请随时告知。 你的详细步骤已经非常全面了,但为了确保一切顺利进行,我们可以在 `package.json` 文件中添加一些必要的配置,并补充一些可能用到的命令。
### 完整项目结构
```
project-root/
├── public/ # 静态资源目录
│ ├── index.html # 主页 HTML 文件
│ └── stats.js # 动态生成视频链接的 JavaScript 文件
├── server.js # 后端服务器脚本
├── package.json # 项目依赖配置文件
└── README.md # 读取文档
```
### `package.json` 配置
在项目根目录下创建或编辑 `package.json` 文件,确保包含必要的依赖和启动命令:
**package.json**
```json
{
"name": "nba-stats",
"version": "1.0.0",
"description": "NBA 比赛信息展示系统",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.2",
"body-parser": "^1.20.2"
}
}
```
### 步骤说明
1. **创建项目目录结构**
```bash
mkdir nba-stats
cd nba-stats
```
2. **初始化 Node.js 项目**
```bash
npm init -y
```
3. **安装必要的依赖**
```bash
npm install express body-parser --save
```
4. **设置 `public` 目录和静态资源文件**
在 `public` 文件夹中创建 `index.html` 和 `stats.js`。
**public/index.html**
```html
NBA 比赛信息
NBA 比赛信息
```
**public/static/stats.js**
```javascript
const statsData = {
date: "2023-10-05",
teams: ["勇士", "国王"],
videos: [
{ season: "第一节", url: "http://example.com/video1" },
{ season: "全场完整录像", url: "http://example.com/full_game" },
{ season: "上半场", url: "http://example.com/half1" },
{ season: "下半场", url: "http://example.com/half2" }
]
};
const statsContainer = document.getElementById('stats-container');
statsData.videos.forEach(video => {
const videoElement = document.createElement('div');
videoElement.className = 'video-link';
const link = document.createElement('a');
link.href = video.url;
link.textContent = `[${statsData.teams[0]} vs ${statsData.teams[1]}] ${video.season}`;
videoElement.appendChild(link);
statsContainer.appendChild(videoElement);
});
```
5. **编写后端服务器代码**
在项目根目录下创建 `server.js` 文件。
**server.js**
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// 使用 body-parser 解析 POST 请求体
app.use(bodyParser.json());
// 提供静态资源
app.use(express.static('public'));
// 路由:提供比赛信息接口
app.get('/stats', (req, res) => {
const statsData = {
date: "2023-10-05",
teams: ["勇士", "国王"],
videos: [
{ season: "第一节", url: "http://example.com/video1" },
{ season: "全场完整录像", url: "http://example.com/full_game" },
{ season: "上半场", url: "http://example.com/half1" },
{ season: "下半场", url: "http://example.com/half2" }
]
};
res.json(statsData);
});
// 启动服务器
const PORT = process.env.PORT