HTTP Module (HTTP Server)
HTTP Module: ساخت سرور HTTP در Node.js 🌐
ماژول http برای ساخت HTTP server و client استفاده میشه. بیایید یک سرور ساده بسازیم!
const http = require('http');
// ساخت HTTP server
const server = http.createServer((req, res) => {
// تنظیم header
res.writeHead(200, { 'Content-Type': 'text/plain' });
// ارسال response
res.end('Hello from Node.js Server!');
});
// گوش دادن به port 3000
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
کار با Request و Response:
const http = require('http');
const server = http.createServer((req, res) => {
// گرفتن URL و Method
console.log('Method:', req.method);
console.log('URL:', req.url);
// Route handling
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('Home Page
');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('About Page
');
} else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('404 Not Found
');
}
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
خواندن Request Body:
const http = require('http');
const server = http.createServer((req, res) => {
let body = '';
// جمعآوری data chunks
req.on('data', chunk => {
body += chunk.toString();
});
// وقتی data کامل شد
req.on('end', () => {
console.log('Body:', body);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: body }));
});
});
server.listen(3000);
💡 نکته: برای پروژههای واقعی، از Express.js استفاده کنید! اون خیلی سادهتر و قدرتمندتره!
✅ یاد گرفتید: http module پایه و اساس همه web servers در Node.js است!
آماده رفتن به درس بعدی هستید؟
این درس را به پایان رساندید و میتوانید به درس بعدی بروید.