server.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const http = require('http');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const PORT = process.env.PORT || 11022;
  5. const ROOT_DIR = path.join(__dirname);
  6. const server = http.createServer((req, res) => {
  7. let filePath = path.join(ROOT_DIR, req.url === '/' ? '/index.html' : req.url);
  8. // SPA fallback: 所有路由都返回 index.html
  9. const extname = path.extname(filePath);
  10. if (extname === '' || !['.html', '.js', '.css', '.jpg', '.jpeg', '.png', '.gif', '.svg', '.ico'].includes(extname)) {
  11. filePath = path.join(ROOT_DIR, 'index.html');
  12. }
  13. const contentType = {
  14. '.html': 'text/html',
  15. '.js': 'application/javascript',
  16. '.css': 'text/css',
  17. '.jpg': 'image/jpeg',
  18. '.png': 'image/png'
  19. }[extname] || 'application/octet-stream';
  20. fs.readFile(filePath, (err, content) => {
  21. if (err) {
  22. res.writeHead(500);
  23. res.end('Error');
  24. } else {
  25. res.writeHead(200, {
  26. 'Content-Type': contentType,
  27. 'Access-Control-Allow-Origin': '*'
  28. });
  29. res.end(content, 'utf-8');
  30. }
  31. });
  32. });
  33. server.listen(PORT, () => {
  34. console.log(`Server running at http://localhost:${PORT}/`);
  35. console.log(`SPA fallback enabled - all routes return index.html`);
  36. });