Node.js
بناء HTTP Server في Node.js — دليل شامل 2026
📅 2026-11-05⏱ 8 دقائق قراءة
في المقال السابق، تعلمت 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)
<table>
<thead>
<tr>
<th>الكود</th>
<th>المعنى</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>200</strong></td>
<td>OK — نجح الطلب</td>
</tr>
<tr>
<td><strong>201</strong></td>
<td>Created — تم الإنشاء</td>
</tr>
<tr>
<td><strong>301</strong></td>
<td>Moved Permanently — نقل دائم</td>
</tr>
<tr>
<td><strong>400</strong></td>
<td>Bad Request — طلب خاطئ</td>
</tr>
<tr>
<td><strong>401</strong></td>
<td>Unauthorized — غير مصرح</td>
</tr>
<tr>
<td><strong>403</strong></td>
<td>Forbidden — ممنوع</td>
</tr>
<tr>
<td><strong>404</strong></td>
<td>Not Found — غير موجود</td>
</tr>
<tr>
<td><strong>500</strong></td>
<td>Internal Server Error — خطأ في السيرفر</td>
</tr>
</tbody>
</table>
## أول HTTP Server
Node.js يحتوي على وحدة **`http`** المدمجة.
### الكود الأساسي:
```javascript
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");
});
```
### التشغيل:
```bash
node server.js
```
**النتيجة:**
```
🚀 السيرفر يعمل على http://localhost:3000
```
افتح المتصفح على `http://localhost:3000` — سترى:
```
مرحباً من Node.js HTTP Server!
```
**🎉 مبروك! بنيت أول HTTP Server!**
## شرح الكود
<table>
<thead>
<tr>
<th>الجزء</th>
<th>الشرح</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>require("http")</code></td>
<td>استيراد وحدة HTTP</td>
</tr>
<tr>
<td><code>http.createServer()</code></td>
<td>إنشاء سيرفر جديد</td>
</tr>
<tr>
<td><code>(req, res) => { }</code></td>
<td>دالة تُنفَّذ لكل طلب</td>
</tr>
<tr>
<td><code>res.writeHead()</code></td>
<td>تعيين headers و status code</td>
</tr>
<tr>
<td><code>res.end()</code></td>
<td>إنهاء الاستجابة</td>
</tr>
<tr>
<td><code>server.listen()</code></td>
<td>الاستماع على منفذ</td>
</tr>
</tbody>
</table>
## فهم `req` و `res`
### `req` (Request)
```javascript
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)
```javascript
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
res.write("الجزء الأول\n");
res.write("الجزء الثاني\n");
res.end("النهاية");
```
## التوجيه (Routing)
**التوجيه** هو **توجيه الطلبات** إلى معالجات مختلفة حسب URL.
```javascript
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
```javascript
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end("<h1>عنوان</h1><p>فقرة</p>");
```
### 2. JSON
```javascript
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ message: "مرحباً", success: true }));
```
### 3. نص عادي
```javascript
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end("نص عادي");
```
### 4. ملف
```javascript
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)
```javascript
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);
```
## تقديم الملفات الثابتة
```javascript
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 بسيط
```javascript
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: سيرفر بسيط
أنشئ سيرفراً يعيد "مرحباً".
**الحل:**
```javascript
const http = require("http");
http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end("مرحباً");
}).listen(3000);
```
### تمرين 2: صفحتان
أنشئ سيرفراً بصفحتين: `/` و `/about`.
**الحل:**
```javascript
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.
**الحل:**
```javascript
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 ويعيده.
**الحل:**
```javascript
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 وأرسله.
**الحل:**
```javascript
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: عداد الزوار
احفظ عدد الزوار وأعده.
**الحل:**
```javascript
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: وقت السيرفر
أعد وقت السيرفر الحالي.
**الحل:**
```javascript
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`
**السبب:** المنفذ مشغول.
**الحل:** استخدم منفذاً آخر:
```javascript
const PORT = process.env.PORT || 3001;
```
**أو** أوقف العملية السابقة:
```bash
# ويندوز
netstat -ano | findstr :3000
taskkill /PID <PID> /F
```
### 🔴 المشكلة 2: السيرفر لا يتحدّث
**السبب:** Node.js لا يعيد التشغيل تلقائياً.
**الحل:** استخدم `nodemon`:
```bash
npx nodemon server.js
```
### 🔴 المشكلة 3: CORS Error
**السبب:** الطلب من نطاق مختلف.
**الحل:** أضف headers CORS:
```javascript
res.setHeader("Access-Control-Allow-Origin", "*");
```
### 🔴 المشكلة 4: `req.body` فارغ
**السبب:** لم تقرأ `body`.
**الحل:**
```javascript
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
console.log(body);
});
```
### 🔴 المشكلة 5: الأحرف العربية تظهر مشوهة
**السبب:** لم تُحدد `charset=utf-8`.
**الحل:**
```javascript
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
```
## جدول رؤوس HTTP المهمة
<table>
<thead>
<tr>
<th>الرأس (Header)</th>
<th>الوظيفة</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Content-Type</code></td>
<td>نوع المحتوى</td>
</tr>
<tr>
<td><code>Content-Length</code></td>
<td>طول المحتوى</td>
</tr>
<tr>
<td><code>Access-Control-Allow-Origin</code></td>
<td>CORS</td>
</tr>
<tr>
<td><code>Cache-Control</code></td>
<td>التخزين المؤقت</td>
</tr>
<tr>
<td><code>Set-Cookie</code></td>
<td>تعيين كوكي</td>
</tr>
</tbody>
</table>
## قائمة تحقق نهائية
<table>
<thead>
<tr>
<th>المهمة</th>
<th>الحالة</th>
</tr>
</thead>
<tbody>
<tr>
<td>فهم HTTP Server</td>
<td>⬜</td>
</tr>
<tr>
<td>بناء سيرفر بسيط</td>
<td>⬜</td>
</tr>
<tr>
<td>فهم req و res</td>
<td>⬜</td>
</tr>
<tr>
<td>التوجيه (Routing)</td>
<td>⬜</td>
</tr>
<tr>
<td>إرسال JSON</td>
<td>⬜</td>
</tr>
<tr>
<td>معالجة POST</td>
<td>⬜</td>
</tr>
<tr>
<td>حل التمارين الثمانية</td>
<td>⬜</td>
</tr>
</tbody>
</table>
## ماذا بعد هذا المقال؟
الآن بعد أن أتقنت HTTP Server، أنت جاهز للمقال التالي:
1. **Express.js** — إطار عمل يبسط بناء السيرفرات.
2. **الراوتر (Router)** — تنظيم المسارات.
3. **بناء REST API** — واجهات برمجية احترافية.
## الخلاصة
في هذا المقال، تعلمت:
- ✅ ما هو HTTP Server.
- ✅ بروتوكول HTTP.
- ✅ أكواد الحالة.
- ✅ بناء سيرفر بسيط.
- ✅ التوجيه (Routing).
- ✅ إرسال أنواع مختلفة (HTML, JSON).
- ✅ معالجة POST.
- ✅ تقديم الملفات الثابتة.
- ✅ حل 8 تمارين عملية.
**تذكر:** HTTP Server هو **أساس** كل تطبيق ويب. فهمه جيداً.