Allpool on samm-sammuline juhend, kuidas käivitada lihtne Node.js + Express REST API ja sellele brauserist andmeid lisada (ilma Postmanita). Sobib nii CodeSandbox kui ka VS Code jaoks.
npm init -y
npm install express cors
// index.js
const express = require("express");
const cors = require("cors");
const path = require("path");
const app = express();
app.use(cors());
app.use(express.json());
// Sinu statiline esipaneel (public/admin.html)
app.use("/", express.static(path.join(__dirname, "public")));
let widgets = [
{ id: 1, name: "Foo", price: 9.99 },
{ id: 2, name: "Bar", price: 19.99 },
{ id: 3, name: "Baz", price: 29.99 },
];
app.get("/widgets", (req, res) => res.json(widgets));
app.get("/widgets/:id", (req, res) => {
const id = Number(req.params.id);
const w = widgets.find(x => x.id === id);
if (!w) return res.status(404).json({ error: "Widget not found" });
res.json(w);
});
app.post("/widgets", (req, res) => {
const { name, price } = req.body;
if (!name || typeof name !== "string" || name.trim() === "")
return res.status(400).json({ error: 'Field "name" is required (string).' });
if (price === undefined || isNaN(Number(price)) || Number(price) < 0)
return res.status(400).json({ error: 'Field "price" is required (number ≥ 0).' });
const newWidget = { id: widgets.length + 1, name: name.trim(), price: Number(price) };
widgets.push(newWidget);
res.status(201).json(newWidget);
});
app.delete("/widgets/:id", (req, res) => {
const id = Number(req.params.id);
const i = widgets.findIndex(x => x.id === id);
if (i === -1) return res.status(404).json({ error: "Widget not found" });
const removed = widgets.splice(i, 1)[0];
res.json({ deleted: removed });
});
app.put("/widgets/:id", (req, res) => {
const id = Number(req.params.id);
const w = widgets.find(x => x.id === id);
if (!w) return res.status(404).json({ error: "Widget not found" });
const { name, price } = req.body;
if (name !== undefined) {
if (typeof name !== "string" || name.trim() === "")
return res.status(400).json({ error: 'Field "name" must be non-empty string.' });
w.name = name.trim();
}
if (price !== undefined) {
if (isNaN(Number(price)) || Number(price) < 0)
return res.status(400).json({ error: 'Field "price" must be number ≥ 0.' });
w.price = Number(price);
}
res.json(w);
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`API running at http://localhost:${PORT}`);
});
{
"name": "rest-api-csb",
"version": "1.0.0",
"main": "index.js",
"type": "commonjs",
"scripts": { "start": "node index.js" },
"dependencies": { "cors": "^2.8.5", "express": "^4.19.2" }
}
node index.js
Loo fail public/admin.html ning ava /admin.html. Nii saad andmeid lisada/vaadata/kustutada ilma Postmanita.
Pärast lisamist näed tulemust:
const API = 'http://localhost:8080'.
app.use(cors()).app.use(express.json()).