HTTP moduli
O‘rnatilgan HTTP moduli
Node.js HTTP serverlarini yaratish va HTTP so‘rovlarini amalga oshirish imkonini beruvchi kuchli o‘rnatilgan HTTP modulini o‘z ichiga oladi.
Ushbu modul Node.js da veb-ilovalar va API yaratish uchun zarur.
Asosiy xususiyatlar
- So‘rovlarni bajarish va javoblarni yuborish uchun HTTP serverlarini yarating
- Boshqa serverlarga HTTP so‘rovlarini yuboring
- Handle different HTTP methods (GET, POST, PUT, DELETE, etc.)
- So‘rov va javob sarlavhalari bilan ishlash
- Katta hajmdagi ma’lumotlar (payload) uchun stream ma’lumotlarini ishlating
Shu jumladan HTTP moduli
HTTP modulidan foydalanish uchun uni require() usuli yordamida ilovangizga kiriting:
// Using CommonJS require (Node.js default)
const http = require('http');
// Or using ES modules (Node.js 14+ with "type": "module" in package.json)
// import http from 'http';
HTTP serverini yaratish
HTTP modulining createServer() usuli belgilangan portdagi so‘rovlarni tinglaydigan va har bir so‘rov uchun callback funksiyasi qilish funksiyasini bajaradigan HTTP serverini yaratadi.
Asosiy HTTP serveriga misol
// Import the HTTP module
const http = require('http');
// Create a server object
const server = http.createServer((req, res) => {
// Set the response HTTP header with HTTP status and Content type
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send the response body as 'Hello, World!'
res.end('Hello, World!\n');
});
// Define the port to listen on
const PORT = 3000;
// Start the server and listen on the specified port
server.listen(PORT, 'localhost', () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Misolni ishga tushirish »
Kodeksni tushunish
http.createServer()- Yangi HTTP server namunasini yaratadi- The callback function is executed for each request with two parameters:
req- The request object (http.IncomingMessage)res- The response object (http.ServerResponse)
res.writeHead()- Javob holati kodi va sarlavhalarini o‘rnatadires.end()- Javobni yuboradi va ulanishni tugatadiserver.listen()- serverni belgilangan portda ishga tushiradi
Serverni ishga tushirish
- Kodni
server.jsnomli faylga saqlang - Node.js yordamida serverni ishga tushiring:
node server.js
Javobni ko‘rish uchun brauzeringizda http://localhost:3000 saytiga tashrif buyuring.
HTTP sarlavhalari bilan ishlash
HTTP sarlavhalari sizning javobingiz bilan qo‘shimcha ma’lumot yuborish imkonini beradi.
res.writeHead() metodi holat kodi va javob sarlavhalarini belgilash uchun ishlatiladi.
Javob sarlavhalarini sozlash
Misol: Bir nechta sarlavhalarni belgilash
const http = require('http');
const server = http.createServer((req, res) => {
// Set status code and multiple headers
res.writeHead(200, {
'Content-Type': 'text/html',
'X-Powered-By': 'Node.js',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Set-Cookie': 'sessionid=abc123; HttpOnly'
});
res.end('<h1>Hello, World!</h1>');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Misolni ishga tushirish »
Umumiy HTTP holat kodlari
| Kod | Xabar | Tavsif |
|---|---|---|
| 200 | OK | Muvaffaqiyatli HTTP so‘rovlari uchun standart javob |
| 201 | Yaratilgan | So‘rov bajarildi va yangi resurs yaratildi |
| 301 | Doimiy ko‘chirildi | Resurs yangi URL manziliga ko‘chirildi |
| 400 | Noto‘g‘ri so‘rov | Mijoz xatosi tufayli server so‘rovni bajara olmaydi |
| 401 | Ruxsatsiz | Autentifikatsiya talab qilinadi |
| 403 | Taqiqlangan | Server so‘rovga ruxsat berishni rad etadi |
| 404 | Topilmadi | So‘ralgan manba topilmadi |
| 500 | Serverdagi ichki xatolik | Kutilmagan holat yuzaga keldi |
Umumiy javob sarlavhalari
Content-Type: Tarkibning media turini belgilaydi (masalan, matn/html, ilova/json)Content-Length: Javob tanasining baytdagi uzunligiLocation: Qayta yo‘naltirishda foydalaniladi (3xx holat kodlari bilan)Set-Cookie: Mijozda HTTP cookie-fayllarini o‘rnatadiCache-Control: Keshlash mexanizmlari bo‘yicha ko‘rsatmalarAccess-Control-Allow-Origin: CORS qo‘llab-quvvatlash uchun
O‘qish so‘rovi sarlavhalari
req.headers obyekti yordamida so‘rov sarlavhalariga kirishingiz mumkin:
const http = require('http');
const server = http.createServer((req, res) => {
// Log all request headers
console.log('Request Headers:', req.headers);
// Get specific headers (case-insensitive)
const userAgent = req.headers['user-agent'];
const acceptLanguage = req.headers['accept-language'];
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`User-Agent: ${userAgent}\nAccept-Language: ${acceptLanguage}`);
});
server.listen(3000);
Misolni ishga tushirish »
URL manzillar va so‘rov stringlari (query string) bilan ishlash
Node.js URL manzillari va so‘rov stringlari (query string) bilan ishlash uchun o‘rnatilgan modullarni taqdim etadi, bu URLning turli qismlarini boshqarish va so‘rov parametrlarini tahlil qilishni osonlashtiradi.
So‘rov URL manziliga kirish
req.url xususiyati so‘ralgan URL stringini, jumladan, har qanday so‘rov parametrlarini o‘z ichiga oladi.
Bu http.IncomingMessage obyektining bir qismi.
Misol: Asosiy URL bilan ishlash
const http = require('http');
const server = http.createServer((req, res) => {
// Get the URL and HTTP method
const { url, method } = req;
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`You made a ${method} request to ${url}`);
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Misolni ishga tushirish »
URL moduli yordamida URL manzillarini tahlil qilish
URL moduli URL manzilini aniqlash va tahlil qilish uchun yordamchi dasturlarni taqdim etadi.
U URL stringini URLning har bir qismi uchun xususiyatlarga ega URL obyektiga ajratishi mumkin.
Misol: URL-manzillarni tahlil qilish
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
// Parse the URL
const parsedUrl = url.parse(req.url, true);
// Get different parts of the URL
const pathname = parsedUrl.pathname; // The path without query string
const query = parsedUrl.query; // The query string as an object
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
pathname,
query,
fullUrl: req.url
}, null, 2));
});
server.listen(3000);
Misol so‘rovlar va javoblar
Quyidagi so‘rov uchun:
GET /products?category=electronics&sort=price&page=2 HTTP/1.1
Server javob beradi:
{
"pathname": "/products",
"query": {
"category": "electronics",
"sort": "price",
"page": "2"
},
"fullUrl": "/products?category=electronics&sort=price&page=2"
}
So‘rov stringlari (query string) bilan ishlash
So‘rov stringini yanada ilg‘or ishlov berish uchun siz querystring modulidan foydalanishingiz mumkin:
Misol: querystring modulidan foydalanish
const http = require('http');
const { URL } = require('url');
const querystring = require('querystring');
const server = http.createServer((req, res) => {
// Using the newer URL API (Node.js 10+)
const baseURL = 'http://' + req.headers.host + '/';
const parsedUrl = new URL(req.url, baseURL);
// Get query parameters
const params = Object.fromEntries(parsedUrl.searchParams);
// Example of building a query string
const queryObj = {
name: 'John Doe',
age: 30,
interests: ['programming', 'music']
};
const queryStr = querystring.stringify(queryObj);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
path: parsedUrl.pathname,
params,
exampleQueryString: queryStr
}, null, 2));
});
server.listen(3000);
Misolni ishga tushirish »
Umumiy URL tahlil usullari
url.parse(urlString, [parseQueryString], [slashesDenoteHost]): URL stringini tahlil qilib, obyektga aylantirishurl.format(urlObject): URL obyektini URL stringiga formatlashurl.resolve(from, to): Asosiy URLga nisbatan maqsadli URL manzilini hal qilishnew URL(input, [base]): WHATWG URL API (yangi kod uchun tavsiya etiladi)querystring.parse(str, [sep], [eq], [options]): So‘rov stringini obyektga tahlil qilishquerystring.stringify(obj, [sep], [eq], [options]): Obyektni so‘rov stringiga aylantiring
Turli xil HTTP usullari bilan ishlash
RESTful API’lar resurslar ustida turli amallarni bajarish uchun odatda turli HTTP metodlaridan (GET, POST, PUT, DELETE va boshqalar) foydalanadi.
Node.js HTTP serverida turli HTTP usullaridan qanday foydalanish mumkin:
Misol: Bir nechta HTTP usullari bilan ishlash
const http = require('http');
const { URL } = require('url');
// In-memory data store (for demonstration)
let todos = [
{ id: 1, task: 'Learn Node.js', completed: false },
{ id: 2, task: 'Build an API', completed: false }
];
const server = http.createServer((req, res) => {
const { method, url } = req;
const parsedUrl = new URL(url, `http://${req.headers.host}`);
const pathname = parsedUrl.pathname;
// Set CORS headers (for development)
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
// Handle preflight requests
if (method === 'OPTIONS') {
res.writeHead(204);
res.end();
return;
}
// Route: GET /todos
if (method === 'GET' && pathname === '/todos') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(todos));
}
// Route: POST /todos
else if (method === 'POST' && pathname === '/todos') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const newTodo = JSON.parse(body);
newTodo.id = todos.length > 0 ? Math.max(...todos.map(t => t.id)) + 1 : 1;
todos.push(newTodo);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(newTodo));
} catch (error) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
}
// Route: PUT /todos/:id
else if (method === 'PUT' && pathname.startsWith('/todos/')) {
const id = parseInt(pathname.split('/')[2]);
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const updatedTodo = JSON.parse(body);
const index = todos.findIndex(t => t.id === id);
if (index === -1) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Todo not found' }));
} else {
todos[index] = { ...todos[index], ...updatedTodo };
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(todos[index]));
}
} catch (error) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
}
// Route: DELETE /todos/:id
else if (method === 'DELETE' && pathname.startsWith('/todos/')) {
const id = parseInt(pathname.split('/')[2]);
const index = todos.findIndex(t => t.id === id);
if (index === -1) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Todo not found' }));
} else {
todos = todos.filter(t => t.id !== id);
res.writeHead(204);
res.end();
}
}
// 404 Not Found
else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
APIni cURL bilan sinab ko‘rish
Ushbu APIni cURL buyruqlari yordamida sinab ko‘rishingiz mumkin:
1. Barcha topshiriqlarni oling
curl http://localhost:3000/todos
2. Yangi vazifa yarating
curl -X POST http://localhost:3000/todos \
-H "Content-Type: application/json" \
-d '{"task":"New Task","completed":false}'
3. Vazifani yangilang
curl -X PUT http://localhost:3000/todos/1 \
-H "Content-Type: application/json" \
-d '{"completed":true}'
4. Vazifani o‘chiring
curl -X DELETE http://localhost:3000/todos/1
HTTP usullari uchun eng yaxshi amaliyotlar
- GET: Resurs yoki resurslar to‘plamini oling (idempotent bo‘lishi kerak)
- POST: Yangi resurs yarating (idempotent emas)
- PUT: Mavjud resursni yangilang yoki agar mavjud bo‘lmasa, uni yarating (idempotent)
- PATCH: Resursni qisman yangilang
- O‘CHIRISh: Resursni o‘chirish (idempotent)
- HEAD: GET bilan bir xil, lekin javob organisiz
- OPTIONS: Maqsadli manba uchun aloqa imkoniyatlarini tavsiflang
Xato bilan ishlash
Har doim xatoni to‘g‘ri hal qilish va tegishli HTTP holat kodlarini kiriting:
200 OK- Muvaffaqiyatli GET/PUT/PATCH201 Created- Resursni muvaffaqiyatli yaratish204 No Content- Muvaffaqiyatli O‘CHIRISH400 Bad Request- so‘rov ma’lumotlari noto‘g‘ri401 Unauthorized- Autentifikatsiya zarur403 Forbidden- Ruxsatlar yetarli emas404 Not Found- Resurs mavjud emas500 Internal Server Error- Server tomonidagi xato
Oqimli javoblar
Node.js oqimlari katta hajmdagi ma’lumotlarni samarali boshqarish uchun kuchli. HTTP moduli o‘qish so‘rovi organlari va javoblarni yozish uchun streamlar bilan yaxshi ishlaydi.
Misol: Katta faylni oqimlash
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
// Get the file path from the URL
const filePath = path.join(__dirname, req.url);
// Check if file exists
fs.access(filePath, fs.constants.F_OK, (err) => {
if (err) {
res.statusCode = 404;
res.end('File not found');
return;
}
// Get file stats
fs.stat(filePath, (err, stats) => {
if (err) {
res.statusCode = 500;
res.end('Server error');
return;
}
// Set appropriate headers
res.setHeader('Content-Length', stats.size);
res.setHeader('Content-Type', 'application/octet-stream');
// Create read stream and pipe to response
const stream = fs.createReadStream(filePath);
// Handle errors
stream.on('error', (err) => {
console.error('Error reading file:', err);
if (!res.headersSent) {
res.statusCode = 500;
res.end('Error reading file');
}
});
// Pipe the file to the response
stream.pipe(res);
});
});
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`File server running at http://localhost:${PORT}/`);
});
Streamingning afzalliklari
- Xotira samaradorligi: hamma narsani xotiraga yuklash o‘rniga ma’lumotlarni qismlarga bo‘lib qayta ishlaydi
- Birinchi baytgacha tezroq vaqt: Ma’lumotlar mavjud bo‘lishi bilanoq jo‘natishni boshlaydi
- Orqaga bosim bilan ishlov berish: o‘qish oqimini to‘xtatib turish orqali sekin mijozlarni avtomatik tarzda boshqaradi
Streaming uchun umumiy foydalanish holatlari
- Fayllarni yuklash/yuklash
- Haqiqiy vaqtda ma’lumotlarni qayta ishlash
- Proksi so‘rovlar
- Video/audio oqimi
- Jurnalni qayta ishlash
W3Schools Pathfinder
Yutuqlaringizni kuzating – bu bepul!
