Warning: mkdir(): No space left on device in /var/www/hottg/post.php on line 59

Warning: file_put_contents(aCache/aDaily/2025-07-20/post/we_use_js/--): Failed to open stream: No such file or directory in /var/www/hottg/post.php on line 72
👩‍💻 HTTP-ответ с таймером самоуничтожения @Node.JS [ru] | Серверный JavaScript
TG Telegram Group & Channel
Node.JS [ru] | Серверный JavaScript | United States America (US)
Create: Update:

👩‍💻 HTTP-ответ с таймером самоуничтожения

Реализуйте простой HTTP-сервер на Node.js, который возвращает уникальные одноразовые ссылки (вида /once/abc123) и сам удаляет их после одного использования или по истечении 60 секунд — в зависимости от того, что наступит раньше.

При повторном доступе к использованной или истекшей ссылке сервер должен возвращать 410 Gone.

Поведение:

GET-запрос на /create создаёт новую одноразовую ссылку, возвращает её клиенту.

При первом запросе к этой ссылке (/once/<id>) возвращается " Valid link" и она становится недействительной.

Если никто не обратился к ссылке за 60 секунд — она автоматически удаляется, и возвращается "410 Gone" при попытке перейти.


Решение задачи🔽

const http = require('http');
const crypto = require('crypto');

const PORT = 3000;
const links = {}; // { id: { createdAt: timestamp, used: bool } }

function generateId() {
return crypto.randomBytes(6).toString('hex');
}

function cleanupLinks() {
const now =
Date.now();
for (const id in links) {
if (now - links[id].createdAt > 60000 || links[id].used) {
delete links[id];
}
}
}

setInterval(cleanupLinks, 5000); // чистим каждые 5 сек

const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${
req.headers.host}`);

if (url.pathname === '/create') {
const id = generateId();
links[id] = { createdAt:
Date.now(), used: false };
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`/once/${id}`);
return;
}

const match = url.pathname.match(/^\/once\/([a-z0-9]+)$/);
if (match) {
const id = match[1];
const record = links[id];

if (!record || record.used || (
Date.now() - record.createdAt > 60000)) {
res.writeHead(410, { 'Content-Type': 'text/plain' });
res.end('🔒 410 Gone: Link expired or used');
} else {
links[id].used = true;
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(' Valid link');
}
return;
}

res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
});

server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});

👩‍💻 HTTP-ответ с таймером самоуничтожения

Реализуйте простой HTTP-сервер на Node.js, который возвращает уникальные одноразовые ссылки (вида /once/abc123) и сам удаляет их после одного использования или по истечении 60 секунд — в зависимости от того, что наступит раньше.

При повторном доступе к использованной или истекшей ссылке сервер должен возвращать 410 Gone.

Поведение:

GET-запрос на /create создаёт новую одноразовую ссылку, возвращает её клиенту.

При первом запросе к этой ссылке (/once/<id>) возвращается " Valid link" и она становится недействительной.

Если никто не обратился к ссылке за 60 секунд — она автоматически удаляется, и возвращается "410 Gone" при попытке перейти.


Решение задачи🔽

const http = require('http');
const crypto = require('crypto');

const PORT = 3000;
const links = {}; // { id: { createdAt: timestamp, used: bool } }

function generateId() {
return crypto.randomBytes(6).toString('hex');
}

function cleanupLinks() {
const now =
Date.now();
for (const id in links) {
if (now - links[id].createdAt > 60000 || links[id].used) {
delete links[id];
}
}
}

setInterval(cleanupLinks, 5000); // чистим каждые 5 сек

const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${
req.headers.host}`);

if (url.pathname === '/create') {
const id = generateId();
links[id] = { createdAt:
Date.now(), used: false };
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`/once/${id}`);
return;
}

const match = url.pathname.match(/^\/once\/([a-z0-9]+)$/);
if (match) {
const id = match[1];
const record = links[id];

if (!record || record.used || (
Date.now() - record.createdAt > 60000)) {
res.writeHead(410, { 'Content-Type': 'text/plain' });
res.end('🔒 410 Gone: Link expired or used');
} else {
links[id].used = true;
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(' Valid link');
}
return;
}

res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
});

server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
Please open Telegram to view this post
VIEW IN TELEGRAM
👍4😁21


>>Click here to continue<<

Node.JS [ru] | Серверный JavaScript




Share with your best friend
VIEW MORE

United States America Popular Telegram Group (US)


Warning: Undefined array key 3 in /var/www/hottg/function.php on line 115

Fatal error: Uncaught mysqli_sql_exception: Can't create/write to file '/tmp/#sql-temptable-a06e-591f27-2807.MAI' (Errcode: 28 "No space left on device") in /var/www/hottg/function.php:216 Stack trace: #0 /var/www/hottg/function.php(216): mysqli_query() #1 /var/www/hottg/function.php(115): select() #2 /var/www/hottg/post.php(351): daCache() #3 /var/www/hottg/route.php(63): include_once('...') #4 {main} thrown in /var/www/hottg/function.php on line 216