Express ilə veb server

Express 5 ilə REST API: marşrutlar və HTTP metodları, marşrut və sorğu parametrləri, JSON gövdəsi, middleware zənciri (log, `express.json`, `express.static`), xətaların bir yerdə emalı, `Router` və qeydlər üçün CRUD API-nin `fetch` ilə yoxlanması.

  • İrəli
  • 25 dəq
  • 12 sual
  • 39 dərsdən 37-cisi

Bu dərsdə öyrənəcəksən

  • Express tətbiqi yaratmaq, metodlara görə marşrutlar yazmaq və req.params, req.query, req.body-ni oxumaq
  • Middleware zəncirinin necə işlədiyini izah etmək və öz middleware-inizi yazmaq
  • 404 və xəta emal edən middleware ilə bütün xətaları bir yerdə JSON cavablara çevirmək
  • Resursu Router-ə ayırıb qeydlər üçün tam CRUD REST API qurmaq

«Node.js: http modulu ilə veb server» dərsində qeydlər API-si üçün URL ayırıcısı, müntəzəm ifadələr, gövdə oxuyan funksiya və xəta örtüyü lazım oldu — əsl məntiqə qədər onlarla sətir. Express Node.js-in ən köhnə və ən geniş yayılmış veb freymvorklarından biridir. O, eyni req və res obyektlərini saxlayır, üstünə marşrutlaşdırma, middleware və köməkçi metodlar əlavə edir. Dərsdə Express 5 işlədilir; nümunələr 5.2.1 versiyası ilə yoxlanılıb. Eyni ideyalar başqa dillərin freymvorklarında da var, ona görə bir dəfə başa düşmək kifayətdir.

Quraşdırma və ilk tətbiq

  1. Layihə

    Boş qovluqda npm init -y və npm pkg set type=module (ES modulları).

  2. Paket

    npm install express — paket node_modules-a, versiya package.json-a yazılır.

  3. İşə salmaq

    node first-app.mjs; node --watch first-app.mjs faylı saxlayanda serveri yenidən başladır.

JavaScript
// first-app.mjs
import express from 'express';

const app = express();

app.get('/', (req, res) => {
  res.send('Salam from Express!');
});

app.get('/api/time', (req, res) => {
  res.json({ city: 'Baku', utcOffset: '+04:00' });
});

app.listen(3000, () => {
  console.log('Express on http://localhost:3000');
});

Gözlənilən nəticə

Express on http://localhost:3000
JavaScript
// first-client.mjs
for (const path of ['/', '/api/time', '/api/weather']) {
  const res = await fetch(`http://localhost:3000${path}`);
  const body = await res.text();
  console.log(`${path} → ${res.status} (${res.headers.get('content-type')})`);
  console.log(res.ok ? body : body.match(/<pre>(.*)<\/pre>/)[1]);
}

Gözlənilən nəticə

/ → 200 (text/html; charset=utf-8)
Salam from Express!
/api/time → 200 (application/json; charset=utf-8)
{"city":"Baku","utcOffset":"+04:00"}
/api/weather → 404 (text/html; charset=utf-8)
Cannot GET /api/weather
Sətirlə res.send text/html qoyur, res.json isə application/json qoyur və JSON.stringify-ı özü çağırır. Naməlum marşrut üçün Express 404 və kiçik HTML səhifəsi qaytarır: Cannot GET /api/weather; müştəri mətni onun <pre> teqindən çıxarır.

Hər HTTP metodu üçün metod var: app.get, app.post, app.put, app.patch, app.delete. Emaledici (req, res) alır, cavab üçün köməkçilər isə zəncirlənir: res.status(201).json(note), res.location('/api/notes/2'), gövdəsiz cavab üçün res.sendStatus(204). app.listen(3000) içəridə http.createServer çağırır.

Davamını oxumaq üçün pulsuz qeydiyyatdan keç

Dərsin qalan bölmələri, test və qeydlər Educora hesabı ilə açılır. Qeydiyyat bir dəqiqə çəkir; irəliləyişin bütün cihazlarında saxlanılır.

Marşrut və sorğu parametrləri

Yoldakı :ad marşrut parametridir: /api/users/:userId/notes/:noteId şablonu /api/users/3/notes/15 ilə üst-üstə düşür və req.params-a { userId: '3', noteId: '15' } yazır. Sorğu sətri req.query-yə ayrılır. Hər ikisində dəyərlər həmişə sətirdir (təkrarlanan açar massiv verir), ona görə onları özünüz çevirin və yoxlayın.

JavaScript
// params-app.mjs
import express from 'express';

const app = express();

app.get('/api/users/:userId/notes/:noteId', (req, res) => {
  const { userId, noteId } = req.params;
  res.json({ userId, noteId, type: typeof noteId });
});

app.get('/api/search', (req, res) => {
  const { q = '', limit = '10' } = req.query;
  res.json({ q, limit: Math.min(Number(limit) || 10, 50), query: req.query });
});

app.listen(3000, () => console.log('Express on http://localhost:3000'));
JavaScript
// params-client.mjs
const paths = [
  '/api/users/3/notes/15',
  '/api/search?q=plov&limit=5',
  '/api/search?q=dolma&limit=999',
  '/api/search?tag=food&tag=baku',
  '/api/users/3/notes',
];
for (const path of paths) {
  const res = await fetch(`http://localhost:3000${path}`);
  console.log(`${res.status} ${path}`);
  if (res.ok) console.log(await res.text());
}

Gözlənilən nəticə

200 /api/users/3/notes/15
{"userId":"3","noteId":"15","type":"string"}
200 /api/search?q=plov&limit=5
{"q":"plov","limit":5,"query":{"q":"plov","limit":"5"}}
200 /api/search?q=dolma&limit=999
{"q":"dolma","limit":50,"query":{"q":"dolma","limit":"999"}}
200 /api/search?tag=food&tag=baku
{"q":"","limit":10,"query":{"tag":["food","baku"]}}
404 /api/users/3/notes
limit=999 50-yə endirildi: URL-dən gələn ədədə etibar etməyin — onu məhdudlaşdırın. ?tag=food&tag=baku massiv verdi. /api/users/3/notes-da :noteId yoxdur, ona görə heç bir marşrut uyğun gəlmir — 404.

Express marşrutları yuxarıdan aşağı yoxlayır və cavab verən ilk uyğun emaledici qalib gəlir. :id istənilən dəyəri tutduğu üçün sabit yollar (/api/notes/stats) parametrli yollardan (/api/notes/:id) əvvəl yazılmalıdır, yoxsa stats sözü id kimi qəbul olunar. Express 5 yol yazılışını da sərtləşdirib: ulduz işarəsinin adı olmalıdır (/files/*splat), istəyə bağlı hissə isə fiqurlu mötərizəyə alınır (/docs{/:page}). Express 4-dən qalan /old/* yazılışı Express 5-də marşrut qeydə alınarkən xəta verir.

JavaScript
// paths.mjs
import express from 'express';
const app = express();
try { app.get('/old/*', (req, res) => res.end()); } catch (e) { console.log('"/old/*" ->', e.constructor.name + ':', e.message.split('\n')[0]); }
app.get('/files/*splat', (req, res) => res.json(req.params));
app.get('/api/notes/stats', (req, res) => res.json({ route: 'stats' }));
app.get('/api/notes/:id', (req, res) => res.json({ route: ':id', id: req.params.id }));
app.get('/docs{/:page}', (req, res) => res.json({ page: req.params.page ?? null }));
const server = app.listen(3001, async () => {
  for (const p of ['/files/a/b/c.txt', '/api/notes/stats', '/api/notes/7', '/docs', '/docs/intro']) {
    const r = await fetch('http://localhost:3001' + p);
    console.log(p, '->', await r.text());
  }
  server.close();
});

Gözlənilən nəticə

"/old/*" -> PathError: Missing parameter name at index 6: /old/*; visit https://git.new/pathToRegexpError for info
/files/a/b/c.txt -> {"splat":["a","b","c.txt"]}
/api/notes/stats -> {"route":"stats"}
/api/notes/7 -> {"route":":id","id":"7"}
/docs -> {"page":null}
/docs/intro -> {"page":"intro"}
Bu fayl serveri 3001 portunda açır, özünə fetch ilə sorğu göndərir və bağlanır. *splat qalan bütün hissələri massiv kimi verir; {/:page} olmayanda req.params.page undefined olur.

Middleware: sorğunun yolu

MiddlewareTərif

Marşrut emaledicisindən əvvəl işləyən (req, res, next) funksiyası. O, req və res-i oxuya və dəyişə, cavabı özü bitirə və ya next() ilə idarəni növbəti funksiyaya ötürə bilər. app.use(fn) onu bütün sorğulara qoşur, onu bir marşruta da vermək olar.

Express middleware və marşrutları əlavə etdiyiniz sıra ilə siyahıda saxlayır və hər sorğunu bu siyahı boyunca ötürür. Ona görə sıra vacibdir: express.json() req.body-ni oxuyan marşrutlardan əvvəl, 404 emaledicisi isə ən sonda olmalıdır. Daxili middleware-lər: express.json() JSON gövdəsini req.body-yə oxuyur (standart limit 100 KB), express.static('public') qovluqdan faylları path traversal müdafiəsi ilə verir, express.urlencoded() adi HTML formalarını oxuyur.

JavaScript
// middleware-app.mjs
import express from 'express';

const app = express();

app.use((req, res, next) => {
  const start = performance.now();
  res.on('finish', () => {
    const ms = (performance.now() - start).toFixed(1);
    console.log(`${req.method} ${req.originalUrl} → ${res.statusCode} (${ms} ms)`);
  });
  next();
});
app.use(express.json({ limit: '10kb' }));
app.use(express.static('public'));

function requireApiKey(req, res, next) {
  if (req.get('X-Api-Key') !== 'demo-key') {
    return res.status(401).json({ error: 'Missing or wrong API key' });
  }
  next();
}

app.post('/api/echo', requireApiKey, (req, res) => {
  res.json({ body: req.body ?? null, type: req.get('Content-Type') ?? null });
});

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

Gözlənilən nəticə

Express on http://localhost:3000
GET / → 200 (8.4 ms)
POST /api/echo → 200 (28.3 ms)
POST /api/echo → 200 (0.6 ms)
POST /api/echo → 401 (0.7 ms)
Log yazan middleware finish hadisəsinə abunə olur, ona görə son status kodunu cavabdan sonra çap edir; millisaniyələr hər işə salınmada fərqlidir. requireApiKey yalnız bir marşruta verilib: açar səhvdirsə, 401 cavabını özü göndərir və next()-i çağırmır.
JavaScript
// middleware-client.mjs
const url = 'http://localhost:3000/api/echo';
const json = { 'Content-Type': 'application/json', 'X-Api-Key': 'demo-key' };

async function show(res) {
  console.log(res.status, await res.text());
}

await show(await fetch('http://localhost:3000/'));
await show(await fetch(url, { method: 'POST', headers: json, body: '{"city":"Baku"}' }));
await show(await fetch(url, { method: 'POST', headers: { 'X-Api-Key': 'demo-key' }, body: 'hi' }));
await show(await fetch(url, { method: 'POST', body: '{}' }));

Gözlənilən nəticə

200 <h1>Notes</h1>

200 {"body":{"city":"Baku"},"type":"application/json"}
200 {"body":null,"type":"text/plain;charset=UTF-8"}
401 {"error":"Missing or wrong API key"}
Birinci sorğunu express.static public/index.html ilə cavablandırdı. text/plain ilə gövdə ayrılmadı və Express 5-də req.body undefined qalır (Express 4 {} verirdi), ona görə cavabda null var.

Xətalar: hamısı üçün bir emaledici

Xəta emaledicisi dörd parametrli middleware-dir: (err, req, res, next) — Express onu parametrlərin sayından tanıyır. O, bütün marşrutlardan sonra gəlir. Emaledici xəta atanda və ya async emaledicinin Promise-i rədd ediləndə Express 5 xətanı ora özü göndərir (Express 4-də asinxron kodda xətanı tutub next(err) çağırmaq lazım idi). Daxili middleware-lərin xətaları da ora gəlir: express.json()-dan qırıq JSON err.status === 400 və err.type === 'entity.parse.failed' ilə gəlir. Siyahının sonundakı adi middleware isə bütün naməlum marşrutları tutur — bu, 404 emaledicisidir.

Express 4

app.get('/api/notes/:id', async (req, res, next) => {
  try {
    res.json(await findNote(req.params.id));
  } catch (error) {
    next(error);
  }
});

Express 5

app.get('/api/notes/:id', async (req, res) => {
  res.json(await findNote(req.params.id));
});
Express 5 async emaledicinin rədd edilmiş Promise-ini xəta emaledicisinə özü ötürür; aşağıdakı layihədə /api/crash marşrutu bunu yoxlayır.
JavaScript
// errors.mjs
export class HttpError extends Error {
  constructor(status, message) {
    super(message);
    this.status = status;
  }
}

export function notFound(req, res) {
  res.status(404).json({ error: `No route for ${req.method} ${req.path}` });
}

export function errorHandler(err, req, res, next) {
  if (err.type === 'entity.parse.failed') {
    return res.status(400).json({ error: 'Body is not valid JSON' });
  }
  const status = err.status ?? 500;
  if (status >= 500) console.error('Unexpected error:', err.message);
  res.status(status).json({
    error: status >= 500 ? 'Internal server error' : err.message,
  });
}
500 cavabında heç vaxt err.message göstərilmir: orada SQL, yollar və ya digər daxili təfərrüatlar ola bilər. Mesaj yalnız loga yazılır.

Router və mini layihə: qeydlər üçün REST API

express.Router() öz marşrutları və middleware-ləri olan kiçik tətbiqdir. Hər resursu ayrıca fayla qoyun və prefikslə qoşun: app.use('/api/notes', notes) — routerin içində yollar qısadır (/, /:id). API-mizdə: istəyə bağlı ?done=true filtri ilə siyahı, birini oxuma, yaratma, qismən dəyişmə (PATCH) və silmə.

SorğuUğurMümkün xətalar
GET /api/notes?done=true200 və massiv—
GET /api/notes/:id200 və qeyd404 — qeyd yoxdur
POST /api/notes201, Location və qeyd400 — səhv JSON və ya text
PATCH /api/notes/:id200 və yenilənmiş qeyd400 — səhv sahə, 404 — qeyd yoxdur
DELETE /api/notes/:id204, gövdə yoxdur404 — qeyd yoxdur
API-nin müqaviləsi: müştəri hər sorğu üçün hansı statusu gözləyə biləcəyini bilir. Belə cədvəli README-yə yazmaq faydalıdır.
JavaScript
// routes/notes.mjs (1/2)
import { Router } from 'express';
import { HttpError } from '../errors.mjs';

export const notes = Router();
const items = [{ id: 1, text: 'Buy bread', done: false }];
let nextId = 2;

function findNote(id) {
  const note = items.find((n) => n.id === Number(id));
  if (!note) throw new HttpError(404, `Note ${id} not found`);
  return note;
}

function checkText(text) {
  if (typeof text !== 'string' || !text.trim()) throw new HttpError(400, 'text must be a non-empty string');
  if (text.length > 200) throw new HttpError(400, 'text is longer than 200 characters');
  return text.trim();
}

notes.get('/', (req, res) => {
  const { done } = req.query;
  res.json(done === undefined ? items : items.filter((n) => String(n.done) === done));
});
notes.get('/:id', (req, res) => res.json(findNote(req.params.id)));
notes.post('/', (req, res) => {
  const note = { id: nextId++, text: checkText(req.body?.text), done: false };
  items.push(note);
  res.status(201).location(`/api/notes/${note.id}`).json(note);
});
findNote və checkText xətanı atır, marşrutlar isə onu tutmur — errorHandler hamısını eyni formada cavablandırır. res.status(201).location(…).json(note) zəncirlənmiş köməkçilərdir.
JavaScript
// routes/notes.mjs (2/2)
notes.patch('/:id', (req, res) => {
  const note = findNote(req.params.id);
  const { text, done } = req.body ?? {};
  if (done !== undefined && typeof done !== 'boolean') throw new HttpError(400, 'done must be true or false');
  if (text !== undefined) note.text = checkText(text);
  if (done !== undefined) note.done = done;
  res.json(note);
});
notes.delete('/:id', (req, res) => {
  items.splice(items.indexOf(findNote(req.params.id)), 1);
  res.sendStatus(204);
});
PATCH yalnız göndərilən sahələri dəyişir və done-un həqiqətən boolean olduğunu yoxlayır: 'yes' sətri keçmir.
JavaScript
// app.mjs
import express from 'express';
import { notes } from './routes/notes.mjs';
import { notFound, errorHandler } from './errors.mjs';

const app = express();

app.use((req, res, next) => {
  res.on('finish', () => console.log(`${req.method} ${req.originalUrl} → ${res.statusCode}`));
  next();
});
app.use(express.json({ limit: '10kb' }));
app.use('/api/notes', notes);
app.get('/api/crash', async () => {
  throw new Error('database is down');
});

app.use(notFound);
app.use(errorHandler);

app.listen(3000, () => console.log('Notes API on http://localhost:3000'));

Gözlənilən nəticə

Notes API on http://localhost:3000
POST /api/notes → 201
PATCH /api/notes/1 → 200
PATCH /api/notes/1 → 400
GET /api/notes?done=false → 200
POST /api/notes → 400
POST /api/notes → 400
DELETE /api/notes/1 → 204
GET /api/notes/1 → 404
GET /api/notes → 200
PUT /api/notes/2 → 404
Unexpected error: database is down
GET /api/crash → 500
Sıra: log → express.json → router → sınaq marşrutu → 404 → xətalar. /api/crash async marşrutun içində verilənlər bazasının sıradan çıxmasını təqlid edir. Çıxış — test zamanı serverin logudur.
JavaScript
// test-api.mjs
const base = 'http://localhost:3000/api';

async function call(method, path, body) {
  const res = await fetch(base + path, {
    method,
    headers: body === undefined ? {} : { 'Content-Type': 'application/json' },
    body,
  });
  const text = await res.text();
  console.log(`${method} ${path} → ${res.status}${text ? ` ${text}` : ''}`);
}

await call('POST', '/notes', JSON.stringify({ text: '  Call Leyla ' }));
await call('PATCH', '/notes/1', JSON.stringify({ done: true }));
await call('PATCH', '/notes/1', JSON.stringify({ done: 'yes' }));
await call('GET', '/notes?done=false');
await call('POST', '/notes', '{"text": ');
await call('POST', '/notes', JSON.stringify({ text: '' }));
await call('DELETE', '/notes/1');
await call('GET', '/notes/1');
await call('GET', '/notes');
await call('PUT', '/notes/2');
await call('GET', '/crash');

Gözlənilən nəticə

POST /notes → 201 {"id":2,"text":"Call Leyla","done":false}
PATCH /notes/1 → 200 {"id":1,"text":"Buy bread","done":true}
PATCH /notes/1 → 400 {"error":"done must be true or false"}
GET /notes?done=false → 200 [{"id":2,"text":"Call Leyla","done":false}]
POST /notes → 400 {"error":"Body is not valid JSON"}
POST /notes → 400 {"error":"text must be a non-empty string"}
DELETE /notes/1 → 204
GET /notes/1 → 404 {"error":"Note 1 not found"}
GET /notes → 200 [{"id":2,"text":"Call Leyla","done":false}]
PUT /notes/2 → 404 {"error":"No route for PUT /api/notes/2"}
GET /crash → 500 {"error":"Internal server error"}
' Call Leyla ' boşluqlardan təmizləndi. PUT üçün marşrut yoxdur və Express 405 deyil, 404 verir — 405 lazımdırsa, onu özünüz yazın. Qırıq JSON-un daxili mesajı (Unexpected end of JSON input) gizlədildi.

Tapşırıq

Express-in middleware zəncirini kiçik formada yazın: runChain(middlewares, req) funksiyalarını sıra ilə çağırsın. next() növbətiyə keçir; funksiya xəta atanda və ya next(error) çağıranda adi funksiyalar ötürülür və birinci 4 parametrli funksiya (err, req, res, next) işləyir. Funksiyanın parametr sayı fn.length-dir.

Tapşırıq · JavaScript
function runChain(middlewares, req) {
  const res = { status: 200, body: null };
  let index = 0;
  function next(error) {
    const fn = middlewares[index++];
    if (!fn) return;
    // error: skip normal functions, call the first fn with 4 parameters
    // no error: call normal functions inside try/catch (catch → next(err)), skip error handlers
  }
  next();
  return res;
}

const logger = (req, res, next) => { console.log('log:', req.url); next(); };
const auth = (req, res, next) => {
  if (!req.user) throw new Error('not logged in');
  next();
};
const handler = (req, res) => { res.body = `Hello, ${req.user}`; };
const onError = (err, req, res, next) => { res.status = 401; res.body = err.message; };

const chain = [logger, auth, handler, onError];
console.log(runChain(chain, { url: '/me', user: 'Aysel' }));
console.log(runChain(chain, { url: '/me' }));
Gözlənilən nəticə
log: /me
{ status: 200, body: 'Hello, Aysel' }
log: /me
{ status: 401, body: 'not logged in' }

Tapşırıq

POST /api/notes üçün yoxlama funksiyası yazın: validateNote(body) xəta mesajları massivini qaytarsın (xəta yoxdursa — boş massiv). Qaydalar: gövdə obyekt olmalıdır (massiv yox); text — boş olmayan sətir, boşluqlarsız ən çox 200 simvol; done varsa, boolean; tags varsa, sətirlər massivi.

Tapşırıq · JavaScript
function validateNote(body) {
  const errors = [];
  // 1) body must be a plain object → otherwise ['body must be a JSON object']
  // 2) text: required, max 200 characters (after trim)
  // 3) done: optional boolean;  4) tags: optional array of strings
  return errors;
}

console.log(validateNote({ text: 'Buy bread', tags: ['home'] }));
console.log(validateNote({ text: '   ', done: 'yes' }));
console.log(validateNote({ text: 'x'.repeat(201), tags: 'work' }));
console.log(validateNote([1, 2]));
Gözlənilən nəticə
[]
[ 'text: required', 'done: must be a boolean' ]
[ 'text: max 200 characters', 'tags: must be an array of strings' ]
[ 'body must be a JSON object' ]

Yadda saxla

  • app.get/post/patch/delete(yol, emaledici); cavab köməkçiləri: res.json, res.status(201), res.location, res.sendStatus(204).
  • req.params (:id) və req.query dəyərləri sətirdir — çevirin, yoxlayın və məhdudlaşdırın.
  • Middleware (req, res, next) əlavə olunma sırası ilə işləyir; express.json() marşrutlardan əvvəl, 404 sonda.
  • 4 parametrli (err, req, res, next) xəta emaledicisidir; Express 5 async emaledicilərin xətalarını ora özü ötürür.
  • Hər resurs ayrıca Router-də, app.use('/api/notes', notes) ilə qoşulur; 500 cavabında daxili təfərrüat göstərilmir.
Dərsdə səhv və ya qeyri-dəqiqlik gördün?

Özünü yoxla

12 sual. Hər düzgün cavab XP qazandırır.

Sual 1 / 12

Sual 1 / 12. app.get('/users/:id', (req, res) => res.json(typeof req.params.id)) marşrutuna GET /users/42 gəlir. Cavab nədir?