const http = require('http'); const fs = require('fs'); const path = require('path'); const url = require('url'); const port = process.env.PORT || 3000; const mimeTypes = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpg', '.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon' }; const server = http.createServer((req, res) => { console.log(`${req.method} ${req.url}`); let filePath = '.' + url.parse(req.url).pathname; // Default to index.html if (filePath === './') { filePath = './index.html'; } const extname = String(path.extname(filePath)).toLowerCase(); const mimeType = mimeTypes[extname] || 'application/octet-stream'; fs.readFile(filePath, (error, content) => { if (error) { if (error.code === 'ENOENT') { // File not found res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found\n'); } else { // Server error res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('500 Internal Server Error\n'); } } else { // Success res.writeHead(200, { 'Content-Type': mimeType, 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization' }); res.end(content, 'utf-8'); } }); }); server.listen(port, () => { console.log(`JCHAT Client Server running at http://localhost:${port}/`); });