index.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. const express = require('express');
  2. const cors = require('cors');
  3. const path = require('path');
  4. const ordersRouter = require('./routes/orders');
  5. const app = express();
  6. const PORT = process.env.PORT || 3000;
  7. app.use(cors());
  8. app.use(express.json({ limit: '50mb' }));
  9. // API 路由
  10. app.use('/api/orders', ordersRouter);
  11. // 健康检查
  12. app.get('/api/health', (req, res) => {
  13. res.json({ status: 'ok', timestamp: new Date().toISOString() });
  14. });
  15. // 生产环境:托管前端静态文件
  16. const distPath = path.join(__dirname, '..', 'web', 'dist');
  17. app.use(express.static(distPath));
  18. // SPA 兜底:所有非API请求返回 index.html
  19. app.get('*', (req, res, next) => {
  20. if (req.path.startsWith('/api')) return next();
  21. res.sendFile(path.join(distPath, 'index.html'), (err) => {
  22. if (err) {
  23. res.status(404).send('前端文件未找到,请先执行 npm run build');
  24. }
  25. });
  26. });
  27. app.listen(PORT, '0.0.0.0', () => {
  28. console.log(`服务器运行在 http://0.0.0.0:${PORT} (NODE_ENV=${process.env.NODE_ENV || 'development'})`);
  29. });