-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
58 lines (47 loc) · 1.6 KB
/
server.js
File metadata and controls
58 lines (47 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
const PORT = process.env.PORT || 63780;
// 提供静态文件服务
app.use('/data', express.static(path.join(__dirname, 'data')));
// 提供前端构建文件
app.use(express.static(path.join(__dirname, 'frontend/build')));
// API路由 - 获取图片列表
app.get('/api/images', (req, res) => {
const indexPath = path.join(__dirname, 'data/dogs/index.json');
fs.readFile(indexPath, 'utf8', (err, data) => {
if (err) {
console.error('读取index.json失败:', err);
return res.status(500).json({ error: '无法读取图片索引' });
}
try {
const indexData = JSON.parse(data);
res.json(indexData);
} catch (parseErr) {
console.error('解析index.json失败:', parseErr);
res.status(500).json({ error: '无法解析图片索引' });
}
});
});
// 特定的JSON文件路由
app.get('/cleaned_index.json', (req, res) => {
res.sendFile(path.join(__dirname, 'data/precise_cleaned/index.json'));
});
app.get('/index.json', (req, res) => {
res.sendFile(path.join(__dirname, 'data/dogs/index.json'));
});
// 所有其他请求都返回React应用
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'frontend/build/index.html'));
});
// 启动服务器
app.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
console.log(`图片文件可访问: http://localhost:${PORT}/data/dogs/`);
});
// 优雅关闭
process.on('SIGINT', () => {
console.log('\n正在关闭服务器...');
process.exit(0);
});