auto-post-marketplace-facebook/server/server.js

46 lines
1.0 KiB
JavaScript

import express from "express";
import fs from "fs";
import bodyParser from "body-parser";
import cors from "cors";
const app = express();
// Cho phép tất cả origin gọi API
app.use(cors());
// parse JSON body
app.use(bodyParser.json());
// API lưu dữ liệu
app.post("/sync", (req, res) => {
const data = req.body;
if (!Array.isArray(data)) {
return res.status(400).json({ error: "Dữ liệu phải là array" });
}
// Thêm field date cho mỗi item
const mapped = data.map((item) => ({
...item,
date: new Date().toISOString(),
}));
// Ghi xuống file
fs.writeFileSync("data.json", JSON.stringify(mapped, null, 2));
res.json({ message: "Đã lưu dữ liệu thành công", saved: mapped.length });
});
// API đọc lại dữ liệu
app.get("/data", (req, res) => {
if (!fs.existsSync("data.json")) {
return res.json([]);
}
const content = fs.readFileSync("data.json", "utf-8");
res.json(JSON.parse(content));
});
app.listen(3000, () => {
console.log("Server chạy tại http://localhost:3000");
});