Перейти к основному содержимому

Первая программа на Node.js

Разработчику Архитектору
Загрузка симулятора первой программы…

Первая программа на Node.js

Соберём небольшой REST API «Заметки» на Express. Это типичный первый шаг после знакомства с синтаксисом JS и асинхронностью.

Теория платформы: Node.js — серверный JavaScript. Справочник: Справочник по Node.


Инициализация проекта

mkdir notes-api && cd notes-api
npm init -y
npm install express
npm install -D nodemon

package.json — добавьте скрипт:

{
"scripts": {
"dev": "nodemon server.js",
"start": "node server.js"
},
"type": "module"
}

"type": "module" включает ESM (import вместо require). Подробнее о модулях — в Node.js.


Сервер

Файл server.js:

import express from 'express';

const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());

const notes = [];
let nextId = 1;

app.get('/health', (_req, res) => {
res.json({ status: 'ok' });
});

app.get('/notes', (_req, res) => {
res.json(notes);
});

app.post('/notes', (req, res) => {
const text = String(req.body?.text ?? '').trim();
if (!text) {
return res.status(400).json({ error: 'text is required' });
}
const note = { id: nextId++, text };
notes.push(note);
res.status(201).json(note);
});

app.delete('/notes/:id', (req, res) => {
const id = Number(req.params.id);
const idx = notes.findIndex((n) => n.id === id);
if (idx === -1) {
return res.status(404).json({ error: 'not found' });
}
notes.splice(idx, 1);
res.status(204).send();
});

app.listen(PORT, () => {
console.log(`API: http://127.0.0.1:${PORT}`);
});

Запуск:

npm run dev

Проверка

curl http://127.0.0.1:3000/health
curl http://127.0.0.1:3000/notes
curl -X POST http://127.0.0.1:3000/notes \
-H "Content-Type: application/json" \
-d "{\"text\": \"Изучить Node\"}"
curl -X DELETE http://127.0.0.1:3000/notes/1

Middleware (следующий шаг)

app.use((req, res, next) => {
console.log(req.method, req.url);
next();
});

Цепочка middleware — основа Express: логирование, CORS, авторизация, обработка ошибок.


Куда дальше

ТемаМатериал
Security APIhelmet, rate-limit
БДpg, Prisma, MongoDB driver
TypeScript на сервереTypeScript
Fullstack ReactNext.js
ДесктопElectron

Production
Для продакшена используйте process manager (systemd, PM2), переменные окружения для секретов и HTTPS за reverse proxy (Nginx, Caddy).


См. также

Другие статьи этого же раздела в боковом меню (как на странице «О разделе»).