Создайте HTTP-сервер на Node.js, который по запросу возвращает случайную цитату из заранее заданного списка.
Ожидаемое поведение:•
Сервер запускается на порту 3000.•
При GET-запросе на /quote сервер возвращает JSON с случайной цитатой.•
При запросе на другой путь возвращается сообщение об ошибке.
Решение задачи
const http = require('http');
const quotes = [
"The only limit to our realization of tomorrow is our doubts of today.",
"Do not watch the clock. Do what it does. Keep going.",
"The future depends on what you do today.",
"Success is not the key to happiness. Happiness is the key to success.",
"Hardships often prepare ordinary people for an extraordinary destiny."
];
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
if (req.url === '/quote' && req.method === 'GET') {
const randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
res.writeHead(200);
res.end(JSON.stringify({ quote: randomQuote }));
} else {
res.writeHead(404);
res.end(JSON.stringify({ error: 'Invalid endpoint' }));
}
});
server.listen(3000, () => {
console.log('Сервер запущен на http://localhost:3000');
});