Your first Express API
Routes, JSON and status codes.
Node.js
import express from "express";
const app = express();
app.use(express.json());
const jobs = [{ id: 1, title: "Intern" }];
app.get("/api/jobs", (req, res) => {
res.json(jobs);
});
app.get("/api/jobs/:id", (req, res) => {
const job = jobs.find((j) => j.id === Number(req.params.id));
if (!job) return res.status(404).json({ error: "Job not found" });
res.json(job);
});
app.post("/api/jobs", (req, res) => {
if (!req.body.title) return res.status(400).json({ error: "Title is required" });
const job = { id: jobs.length + 1, title: req.body.title };
jobs.push(job);
res.status(201).json(job);
});
app.listen(3000, () => console.log("http://localhost:3000"));| Status | Meaning |
|---|---|
200 / 201 | OK / created |
400 | The request is wrong |
401 / 403 | Not signed in / not allowed |
404 | Not found |
500 | The server failed |