بناء HTTP Server في Node.js — دليل شامل 2026
دليل عملي مفصل لبناء HTTP Server في Node.js — الطلبات، الاستجابات، التوجيه، والملفات الثابتة، مع تمارين وحلول
في المقال السابق، تعلمت npm وإدارة الحزم. الآن سنبني HTTP Server — وهو أساس أي تطبيق ويب.
في هذا الدليل العملي، سنأخذك خطوة بخطوة لبناء سيرفر HTTP من الصفر، مع تمارين وحلول.
ما هو HTTP Server؟
HTTP Server هو برنامج يستقبل طلبات (Requests) من المتصفح، ويعيد استجابات (Responses).
تشبيه بسيط: تخيل مطعماً:
- العميل (Client): يطلب طعاماً (Request).
- النادل (Server): يستقبل الطلب ويعالجه.
- الطاهي (Logic): يجهّز الطعام (Response).
- الطعام (Response): يعود للعميل.
بروتوكول HTTP
HTTP = HyperText Transfer Protocol.
الطلب (Request)
يتكون من:
- Method: GET، POST، PUT، DELETE، إلخ.
- URL: العنوان المطلوب.
- Headers: معلومات إضافية.
- Body: البيانات (اختياري).
الاستجابة (Response)
تتكون من:
- Status Code: رقم الحالة (200، 404، 500).
- Headers: معلومات إضافية.
- Body: المحتوى.
أكواد الحالة (Status Codes)
| الكود | المعنى |
|---|---|
| 200 | OK — نجح الطلب |
| 201 | Created — تم الإنشاء |
| 301 | Moved Permanently — نقل دائم |
| 400 | Bad Request — طلب خاطئ |
| 401 | Unauthorized — غير مصرح |
| 403 | Forbidden — ممنوع |
| 404 | Not Found — غير موجود |
| 500 | Internal Server Error — خطأ في السيرفر |
أول HTTP Server
Node.js يحتوي على وحدة http المدمجة.
الكود الأساسي:
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end("مرحباً من Node.js HTTP Server!");
});
server.listen(3000, () => {
console.log("🚀 السيرفر يعمل على http://localhost:3000");
});
التشغيل:
node server.js
النتيجة:
🚀 السيرفر يعمل على http://localhost:3000
افتح المتصفح على http://localhost:3000 — سترى:
مرحباً من Node.js HTTP Server!
🎉 مبروك! بنيت أول HTTP Server!
شرح الكود
| الجزء | الشرح |
|---|---|
require("http") | استيراد وحدة HTTP |
http.createServer() | إنشاء سيرفر جديد |
(req, res) => { } | دالة تُنفَّذ لكل طلب |
res.writeHead() | تعيين headers و status code |
res.end() | إنهاء الاستجابة |
server.listen() | الاستماع على منفذ |
فهم req و res
req (Request)
const server = http.createServer((req, res) => {
console.log("Method:", req.method); // GET
console.log("URL:", req.url); // /
console.log("Headers:", req.headers); // { host, user-agent, ... }
});
res (Response)
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
res.write("الجزء الأول\n");
res.write("الجزء الثاني\n");
res.end("النهاية");
التوجيه (Routing)
التوجيه هو توجيه الطلبات إلى معالجات مختلفة حسب URL.
const http = require("http");
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
res.setHeader("Content-Type", "text/html; charset=utf-8");
// الصفحة الرئيسية
if (url === "/" && method === "GET") {
res.writeHead(200);
res.end("<h1>🏠 الرئيسية</h1>");
return;
}
// صفحة من نحن
if (url === "/about" && method === "GET") {
res.writeHead(200);
res.end("<h1>ℹ️ من نحن</h1>");
return;
}
// API
if (url === "/api/users" && method === "GET") {
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.writeHead(200);
res.end(JSON.stringify([
{ id: 1, name: "أحمد" },
{ id: 2, name: "محمد" },
]));
return;
}
// 404
res.writeHead(404);
res.end("<h1>404 — الصفحة غير موجودة</h1>");
});
server.listen(3000, () => console.log("🚀 على http://localhost:3000"));
إرسال أنواع مختلفة
1. HTML
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end("<h1>عنوان</h1><p>فقرة</p>");
2. JSON
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ message: "مرحباً", success: true }));
3. نص عادي
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end("نص عادي");
4. ملف
const fs = require("fs");
const content = fs.readFileSync("index.html", "utf-8");
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(content);
قراءة body (POST)
const http = require("http");
const server = http.createServer((req, res) => {
if (req.method === "POST" && req.url === "/api/users") {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", () => {
try {
const data = JSON.parse(body);
console.log("البيانات:", data);
res.writeHead(201, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ success: true, user: data }));
} catch (error) {
res.writeHead(400, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ success: false, error: "JSON غير صالح" }));
}
});
return;
}
res.writeHead(404);
res.end("404");
});
server.listen(3000);
تقديم الملفات الثابتة
const http = require("http");
const fs = require("fs");
const path = require("path");
const server = http.createServer((req, res) => {
let filePath = "." + req.url;
if (filePath === "./") {
filePath = "./index.html";
}
const extname = path.extname(filePath);
let contentType = "text/html";
switch (extname) {
case ".js": contentType = "text/javascript"; break;
case ".css": contentType = "text/css"; break;
case ".json": contentType = "application/json"; break;
case ".png": contentType = "image/png"; break;
case ".jpg": contentType = "image/jpeg"; break;
case ".svg": contentType = "image/svg+xml"; break;
}
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === "ENOENT") {
res.writeHead(404);
res.end("404 — غير موجود");
} else {
res.writeHead(500);
res.end("خطأ في السيرفر");
}
return;
}
res.writeHead(200, { "Content-Type": contentType + "; charset=utf-8" });
res.end(content);
});
});
server.listen(3000, () => console.log("🚀 على http://localhost:3000"));
مثال عملي: API بسيط
const http = require("http");
// قاعدة بيانات في الذاكرة
let todos = [
{ id: 1, text: "تعلم Node.js", completed: false },
{ id: 2, text: "بناء API", completed: false },
];
const server = http.createServer((req, res) => {
const { method, url } = req;
res.setHeader("Content-Type", "application/json; charset=utf-8");
// GET /api/todos
if (method === "GET" && url === "/api/todos") {
res.writeHead(200);
res.end(JSON.stringify(todos));
return;
}
// POST /api/todos
if (method === "POST" && url === "/api/todos") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
const data = JSON.parse(body);
const newTodo = {
id: Date.now(),
text: data.text,
completed: false,
};
todos.push(newTodo);
res.writeHead(201);
res.end(JSON.stringify(newTodo));
});
return;
}
// DELETE /api/todos/:id
if (method === "DELETE" && url.startsWith("/api/todos/")) {
const id = parseInt(url.split("/")[3]);
todos = todos.filter((t) => t.id !== id);
res.writeHead(200);
res.end(JSON.stringify({ success: true }));
return;
}
res.writeHead(404);
res.end(JSON.stringify({ error: "المسار غير موجود" }));
});
server.listen(3000, () => console.log("🚀 API على http://localhost:3000"));
تمارين عملية
تمرين 1: سيرفر بسيط
أنشئ سيرفراً يعيد "مرحباً".
الحل:
const http = require("http");
http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end("مرحباً");
}).listen(3000);
تمرين 2: صفحتان
أنشئ سيرفراً بصفحتين: / و /about.
الحل:
const http = require("http");
http.createServer((req, res) => {
res.setHeader("Content-Type", "text/html; charset=utf-8");
if (req.url === "/") {
res.end("<h1>الرئيسية</h1>");
} else if (req.url === "/about") {
res.end("<h1>من نحن</h1>");
} else {
res.writeHead(404);
res.end("<h1>404</h1>");
}
}).listen(3000);
تمرين 3: API JSON
أنشئ سيرفراً يعيد JSON.
الحل:
const http = require("http");
http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ name: "أحمد", age: 25 }));
}).listen(3000);
تمرين 4: معالجة POST
أنشئ endpoint يقبل JSON ويعيده.
الحل:
const http = require("http");
http.createServer((req, res) => {
if (req.method === "POST" && req.url === "/api/echo") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
res.end(body);
});
return;
}
res.writeHead(404);
res.end();
}).listen(3000);
تمرين 5: تقديم ملف HTML
اقرأ ملف HTML وأرسله.
الحل:
const http = require("http");
const fs = require("fs");
http.createServer((req, res) => {
fs.readFile("index.html", "utf-8", (err, data) => {
if (err) {
res.writeHead(404);
res.end("غير موجود");
return;
}
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(data);
});
}).listen(3000);
تمرين 6: عداد الزوار
احفظ عدد الزوار وأعده.
الحل:
const http = require("http");
let visits = 0;
http.createServer((req, res) => {
visits++;
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ visits }));
}).listen(3000);
تمرين 7: وقت السيرفر
أعد وقت السيرفر الحالي.
الحل:
const http = require("http");
http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify({
timestamp: new Date().toISOString(),
uptime: process.uptime(),
}));
}).listen(3000);
تمرين 8: API كامل
ابنِ API كامل للمهام (CRUD).
الحل: (راجع المثال العملي أعلاه)
حل المشاكل الشائعة
🔴 المشكلة 1: EADDRINUSE: address already in use
السبب: المنفذ مشغول.
الحل: استخدم منفذاً آخر:
const PORT = process.env.PORT || 3001;
أو أوقف العملية السابقة:
# ويندوز
netstat -ano | findstr :3000
taskkill /PID <PID> /F
🔴 المشكلة 2: السيرفر لا يتحدّث
السبب: Node.js لا يعيد التشغيل تلقائياً.
الحل: استخدم nodemon:
npx nodemon server.js
🔴 المشكلة 3: CORS Error
السبب: الطلب من نطاق مختلف.
الحل: أضف headers CORS:
res.setHeader("Access-Control-Allow-Origin", "*");
🔴 المشكلة 4: req.body فارغ
السبب: لم تقرأ body.
الحل:
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
console.log(body);
});
🔴 المشكلة 5: الأحرف العربية تظهر مشوهة
السبب: لم تُحدد charset=utf-8.
الحل:
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
جدول رؤوس HTTP المهمة
| الرأس (Header) | الوظيفة |
|---|---|
Content-Type | نوع المحتوى |
Content-Length | طول المحتوى |
Access-Control-Allow-Origin | CORS |
Cache-Control | التخزين المؤقت |
Set-Cookie | تعيين كوكي |
قائمة تحقق نهائية
| المهمة | الحالة |
|---|---|
| فهم HTTP Server | ⬜ |
| بناء سيرفر بسيط | ⬜ |
| فهم req و res | ⬜ |
| التوجيه (Routing) | ⬜ |
| إرسال JSON | ⬜ |
| معالجة POST | ⬜ |
| حل التمارين الثمانية | ⬜ |
ماذا بعد هذا المقال؟
الآن بعد أن أتقنت HTTP Server، أنت جاهز للمقال التالي:
- Express.js — إطار عمل يبسط بناء السيرفرات.
- الراوتر (Router) — تنظيم المسارات.
- بناء REST API — واجهات برمجية احترافية.
الخلاصة
في هذا المقال، تعلمت:
- ✅ ما هو HTTP Server.
- ✅ بروتوكول HTTP.
- ✅ أكواد الحالة.
- ✅ بناء سيرفر بسيط.
- ✅ التوجيه (Routing).
- ✅ إرسال أنواع مختلفة (HTML, JSON).
- ✅ معالجة POST.
- ✅ تقديم الملفات الثابتة.
- ✅ حل 8 تمارين عملية.
تذكر: HTTP Server هو أساس كل تطبيق ويب. فهمه جيداً.
npm وإدارة الحزم في Node.js — دليل شامل 2026
مقدمة في Express.js — دليل شامل 2026
📚 مقالات ذات صلة
مشروع Node.js متكامل — API مع مصادقة JWT 2026
مشروع عملي شامل لبناء API متكامل بـ Node.js و Express و MongoDB — مع مصادقة JWT، رفع الملفات، والنشر
MongoDB مع Node.js — دليل شامل 2026
دليل عملي مفصل لاستخدام MongoDB مع Node.js — Mongoose، Schema، CRUD، العلاقات، مع تمارين وحلول
بناء REST API في Node.js — دليل شامل 2026
دليل عملي مفصل لبناء REST API احترافي — المبادئ، التنظيم، التحقق، والاختبار، مع تمارين وحلول