| 123456789101112131415161718192021222324252627282930313233343536373839404142 |
- const http = require('http');
- const fs = require('fs');
- const path = require('path');
- const PORT = process.env.PORT || 11022;
- const ROOT_DIR = path.join(__dirname);
- const server = http.createServer((req, res) => {
- let filePath = path.join(ROOT_DIR, req.url === '/' ? '/index.html' : req.url);
-
- // SPA fallback: 所有路由都返回 index.html
- const extname = path.extname(filePath);
- if (extname === '' || !['.html', '.js', '.css', '.jpg', '.jpeg', '.png', '.gif', '.svg', '.ico'].includes(extname)) {
- filePath = path.join(ROOT_DIR, 'index.html');
- }
-
- const contentType = {
- '.html': 'text/html',
- '.js': 'application/javascript',
- '.css': 'text/css',
- '.jpg': 'image/jpeg',
- '.png': 'image/png'
- }[extname] || 'application/octet-stream';
-
- fs.readFile(filePath, (err, content) => {
- if (err) {
- res.writeHead(500);
- res.end('Error');
- } else {
- res.writeHead(200, {
- 'Content-Type': contentType,
- 'Access-Control-Allow-Origin': '*'
- });
- res.end(content, 'utf-8');
- }
- });
- });
- server.listen(PORT, () => {
- console.log(`Server running at http://localhost:${PORT}/`);
- console.log(`SPA fallback enabled - all routes return index.html`);
- });
|