sozday-mne-formu-registratsi/server.js

76 lines
2.5 KiB
JavaScript

const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = process.env.PORT || 3000;
const DATA = path.join(__dirname, "data.json");
function readItems() {
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return []; }
}
function writeItems(items) {
fs.writeFileSync(DATA, JSON.stringify(items, null, 2));
}
function sendJSON(res, code, obj) {
const body = JSON.stringify(obj);
res.writeHead(code, {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
"Access-Control-Allow-Headers": "Content-Type"
});
res.end(body);
}
function body(req) {
return new Promise((resolve) => {
let s = "";
req.on("data", (c) => (s += c));
req.on("end", () => { try { resolve(JSON.parse(s || "{}")); } catch (_) { resolve({}); } });
});
}
const MIME = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
".woff2": "font/woff2",
".woff": "font/woff"
};
http.createServer(async (req, res) => {
const url = (req.url || "/").split("?")[0];
if (req.method === "OPTIONS") return sendJSON(res, 204, {});
if (req.method === "GET" && url === "/api/items") {
return sendJSON(res, 200, readItems());
}
if (req.method === "POST" && url === "/api/items") {
const item = await body(req);
if (!item.name || !item.phone) return sendJSON(res, 400, { ok: false, error: "name and phone are required" });
const items = readItems();
items.push({
id: Date.now(),
name: String(item.name).slice(0, 120),
phone: String(item.phone).slice(0, 30),
dept: String(item.dept || "").slice(0, 120),
comment: String(item.comment || "").slice(0, 300),
createdAt: new Date().toISOString()
});
writeItems(items);
return sendJSON(res, 200, { ok: true });
}
const file = url === "/" ? "/index.html" : url;
const full = path.join(__dirname, file);
if (full.startsWith(__dirname) && fs.existsSync(full) && fs.statSync(full).isFile()) {
const mime = MIME[path.extname(full)] || "application/octet-stream";
res.writeHead(200, { "Content-Type": mime });
return res.end(fs.readFileSync(full));
}
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Not found");
}).listen(PORT, () => console.log("Сервер на порту " + PORT));