Asosiy matnga o'tish
ITIT Interview
Node.js

HTTP server va REST

node:http bilan server, so'rov va javob, HTTP metodlari, status kodlar, REST API tamoyillari, CORS va fetch.

O'rganildi: 0 / 5
Progress

Bu nima?

Node.js'ning o'rnatilgan http moduli freymvorksiz HTTP server yaratishga imkon beradi. Express kabi freymvorklar aynan shuning ustiga qurilgan, shuning uchun asosini tushunish muhim.

import http from 'node:http';

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/health') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    return res.end(JSON.stringify({ ok: true }));
  }
  res.writeHead(404).end('Topilmadi');
});

server.listen(3000, () => console.log('http://localhost:3000'));

So'rov tanasini o'qish

req — Readable stream, shuning uchun tana bo'laklab keladi:

async function readJson(req) {
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  return JSON.parse(Buffer.concat(chunks).toString());
}

HTTP metodlari

MetodVazifasiIdempotent
GETMa'lumot olishHa
POSTYangi resurs yaratishYo'q
PUTResursni to'liq almashtirishHa
PATCHQisman yangilashOdatda yo'q
DELETEO'chirishHa

Idempotent — bir xil so'rovni bir necha marta yuborish bir marta yuborish bilan bir xil natija beradi.

Status kodlar

KodMa'nosi
200 OK, 201 Created, 204 No ContentMuvaffaqiyat
301/308 doimiy, 302/307 vaqtinchalikYo'naltirish
400 Bad RequestNoto'g'ri ma'lumot
401 UnauthorizedAutentifikatsiya yo'q
403 ForbiddenRuxsat yo'q
404 Not FoundTopilmadi
409 ConflictZiddiyat (masalan, email band)
422 UnprocessableValidatsiya xatosi
429 Too Many RequestsRate limit
500 Internal Server ErrorServer xatosi

REST tamoyillari

GET    /api/users          ro'yxat (?page=2&limit=20&sort=-createdAt)
GET    /api/users/42       bitta foydalanuvchi
POST   /api/users          yaratish
PATCH  /api/users/42       yangilash
DELETE /api/users/42       o'chirish
GET    /api/users/42/orders  ichki resurs
  • URL'da otlar (resurslar), amal esa HTTP metodida.
  • Ko'plik shakli: /users, /orders.
  • Stateless: har bir so'rov kerakli barcha ma'lumotni (token) o'zi olib keladi.
  • To'g'ri status kodlar va bir xil xato formati.

CORS

Brauzer boshqa domenga (origin) so'rov yuborganda server ruxsat berishi kerak:

res.setHeader('Access-Control-Allow-Origin', 'https://myapp.uz');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PATCH,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');

Content-Type: application/json yoki Authorization sarlavhali so'rovlardan oldin brauzer OPTIONS (preflight) so'rov yuboradi. CORS faqat brauzerda ishlaydi: server-server so'rovlarga ta'sir qilmaydi.

fetch

Node.js 18 dan boshlab fetch o'rnatilgan:

const res = await fetch('https://api.example.com/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Ali' }),
  signal: AbortSignal.timeout(5000),   // 5 soniya timeout
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();

Intervyu savollari

Ushbu sahifada