Vấn đề | Tỷ lệ Gặp Phải | Hậu Quả |
---|---|---|
Port Conflicts | 32% | Server không khởi động được |
Permission Error | 18% | Server crash ngay lập tức |
Memory Leak | 26% | Server ngừng hoạt động không báo |
Với 42.65% developer dùng Node.js và 74% tổ chức hướng đến API-first, đây là vấn đề cộng đồng cần chung tay giải quyết.
fetch('/api/data') .then(response => response.json()) .then(data => console.log(data)); // undefined... 😤
const http = require('http');const server = http.createServer((req, res) => { // Xử lý request ở đây});
// Ngăn chặn chết im lặngserver.on('error', (error) => { const communityFixes = { 'EADDRINUSE': '❌ Port 3000 đang bị chiếm dụng. Fix: lsof -ti:3000 | xargs kill', 'EACCES': '❌ Thiếu quyền truy cập. Fix: dùng sudo hoặc chọn port > 1024', 'ENOTFOUND': '❌ Địa chỉ không hợp lệ. Fix: kiểm tra cấu hình HOST' }; console.error(communityFixes[error.code] || `❌ Lỗi server: ${error.message}`); console.error('💡 Hãy chia sẻ lỗi này trên DEV Community để được hỗ trợ!'); process.exit(1);});
server.listen(3000, () => { console.log('✅ Server chạy trên http://localhost:3000'); console.log('🎯 Mục tiêu: 99.99% uptime (trung bình ngành: 99.45%)'); console.log('🚀 Sẵn sàng để cộng đồng test!');});
const server = http.createServer((req, res) => { const startTime = Date.now(); const requestId = Math.random().toString(36).substr(2, 9);
console.log(`📥 ${requestId} | ${req.method} ${req.url} | ${new Date().toISOString()}`);
try { handleRequest(req, res, requestId, startTime); } catch (error) { console.error(`❌ ${requestId} | LỖI: ${error.message}`); sendErrorResponse(res, 500, 'Có lỗi xảy ra', error.message, requestId, startTime); }});
function sendErrorResponse(res, statusCode, userMessage, debugMessage, requestId, startTime) { const responseTime = Date.now() - startTime; res.statusCode = statusCode; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ success: false, message: userMessage, debug: process.env.NODE_ENV === 'development' ? debugMessage : undefined, meta: { requestId, responseTime: `${responseTime}ms`, timestamp: new Date().toISOString() }, helpUrl: 'https://dev.to/arbythecoder' // Cộng đồng hỗ trợ }, null, 2)); console.log(`❌ ${requestId} | ${statusCode} | ${responseTime}ms`);}
process.on('uncaughtException', (error) => { console.error('💥 CẢNH BÁO CỘNG ĐỒNG - EXCEPTION BỊ BỎ QUA:', error.message); console.error('Stack:', error.stack); console.error('🔄 Đang tắt server an toàn...'); server.close(() => { console.error('✅ Server đã đóng. Thoát tiến trình.'); process.exit(1); });});
process.on('unhandledRejection', (reason) => { console.error('🚫 PROMISE BỊ BỎ QUA:', reason);});
process.on('SIGINT', () => { console.log('\n🛑 Đóng server thân thiện với cộng đồng...'); server.close(() => { console.log('✅ Server đóng an toàn. Hẹn gặp lại trên DEV! 🚀'); process.exit(0); });});
const http = require('http');const PORT = process.env.PORT || 3000;
const bibleVerses = [ { id: 1, verse: "For God so loved the world...", reference: "John 3:16", contributor: "DEV Community" }, { id: 2, verse: "I can do all things through Christ...", reference: "Phil 4:13", contributor: "@arbythecoder" }, { id: 3, verse: "Trust in the Lord with all your heart...", reference: "Prov 3:5-6", contributor: "Community Request" }];
function sendResponse(res, statusCode, data, message, requestId, startTime) { const responseTime = Date.now() - startTime; try { res.statusCode = statusCode; res.setHeader('Content-Type', 'application/json'); res.setHeader('Access-Control-Allow-Origin', '*'); const response = { success: statusCode < 400, message, data, meta: { requestId, responseTime: `${responseTime}ms`, timestamp: new Date().toISOString() }, community: 'Built with DEV Community feedback', author: '@arbythecoder' }; res.end(JSON.stringify(response, null, 2)); console.log(`${statusCode < 400 ? '✅' : '❌'} ${requestId} | ${statusCode} | ${responseTime}ms`); } catch (error) { console.error('❌ Lỗi format response:', error); res.statusCode = 500; res.end('{"error": "Lỗi format response - kiểm tra DEV Community để được giúp"}'); }}
const server = http.createServer((req, res) => { const startTime = Date.now(); const requestId = Math.random().toString(36).substr(2, 9); console.log(`📥 ${requestId} | ${req.method} ${req.url}`);
try { const url = new URL(req.url, `http://${req.headers.host}`); if (url.pathname === '/' && req.method === 'GET') { sendResponse(res, 200, { message: "Chào mừng đến với DEV Community Bible Verse API! 📖", endpoints: [ "GET /verse - Câu thánh kinh ngẫu nhiên", "GET /verse?id=1 - Câu cụ thể", "GET /health - Kiểm tra trạng thái API" ], stats: "Giảm tỉ lệ lỗi API 67% từng endpoint một", github: "Fork me trên GitHub!", devTo: "@arbythecoder - cộng tác" }, 'Tài liệu API tải thành công', requestId, startTime); } else if (url.pathname === '/verse' && req.method === 'GET') { const id = url.searchParams.get('id'); if (id) { const verseId = parseInt(id, 10); if (isNaN(verseId) || verseId < 1) { sendResponse(res, 400, null, 'ID không hợp lệ - Lưu ý: chỉ dùng số nguyên dương', requestId, startTime); return; } const verse = bibleVerses.find(v => v.id === verseId); if (verse) { sendResponse(res, 200, verse, 'Câu thánh kinh cộng đồng được gửi tới! 🙏', requestId, startTime); } else { sendResponse(res, 404, null, `Không tìm thấy câu số ${verseId} - Muốn đóng góp? Liên hệ @arbythecoder`, requestId, startTime); } } else { const randomVerse = bibleVerses[Math.floor(Math.random() * bibleVerses.length)]; sendResponse(res, 200, randomVerse, 'Câu ngẫu nhiên của cộng đồng! ✨', requestId, startTime); } } else if (url.pathname === '/health' && req.method === 'GET') { sendResponse(res, 200, { status: 'healthy', uptime: `${process.uptime().toFixed(2)} giây`, memory: process.memoryUsage(), target: '99.99% uptime (vs trung bình ngành 99.45%)', community: 'Được DEV Community xác nhận!' }, 'Kiểm tra sức khỏe API thành công! 💚', requestId, startTime); } else { sendResponse(res, 404, null, `Route ${url.pathname} không tồn tại - Xem tài liệu trên DEV Community`, requestId, startTime); } } catch (error) { console.error(`❌ ${requestId} | Lỗi xử lý request:`, error); sendResponse(res, 500, null, 'Lỗi nội bộ server - Cần cộng đồng fix', requestId, startTime); }});
curl http://localhost:3000/
curl http://localhost:3000/verse
curl http://localhost:3000/health
curl http://localhost:3000/invalid
(404)curl http://localhost:3000/verse?id=abc
(400)curl http://localhost:3000/verse?id=999
(404)