na-kakuyu-temu-mozhno-sozdat/server.js

79 lines
2.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 readData() {
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return {}; }
}
function parseBody(req) {
return new Promise((resolve) => {
let s = "";
req.on("data", (c) => (s += c));
req.on("end", () => { try { resolve(JSON.parse(s || "{}")); } catch (_) { resolve({}); } });
});
}
function json(res, data, status = 200) {
res.writeHead(status, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" });
res.end(JSON.stringify(data));
}
const routes = {
"GET /api/data": (req, res) => {
const data = readData();
json(res, { ok: true, data });
},
"POST /api/contact": async (req, res) => {
const { name, phone, service } = await parseBody(req);
if (!name || !phone) return json(res, { ok: false, error: "Имя и телефон обязательны" }, 400);
console.log(`📞 Заявка: ${name}, ${phone}, ${service || 'Не указано'}`);
json(res, { ok: true, message: "Заявка отправлена! Мы свяжемся с вами в течение 15 минут." });
}
};
const mimeTypes = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8"
};
http.createServer(async (req, res) => {
const url = req.url.split("?")[0];
const method = req.method;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
if (method === "OPTIONS") {
res.writeHead(204);
return res.end();
}
for (const [route, handler] of Object.entries(routes)) {
const [m, p] = route.split(" ");
if (method !== m) continue;
if (p === url) return handler(req, res);
}
let file = url === "/" ? "/index.html" : url;
const full = path.join(__dirname, file);
if (full.startsWith(__dirname) && fs.existsSync(full) && fs.statSync(full).isFile()) {
const ext = path.extname(full);
const type = mimeTypes[ext] || "application/octet-stream";
res.writeHead(200, { "Content-Type": type });
return res.end(fs.readFileSync(full));
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
}).listen(PORT, () => console.log("Kazakhtelecom site running on port " + PORT));