POST is used to create new resources. When you submit a form or send data to create something new, you’re typically using POST.

How POST Works

So far we’ve been using app.get() to create routes that handle GET requests. Now we’ll use app.post() to create routes that handle POST requests. The structure is the same - we define a path and a handler function - but the HTTP method is different.

From the frontend (what you’ve done before):

fetch("/users", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Bob", email: "bob@example.com" }),
});

On the API side (what we’re learning now):

app.post("/users", (req, res) => {
  // Get name and email from request body
  const { name, email } = req.body;

  // Basic validation
  if (!name || !email) {
    return res.status(400).json({ error: "Name and email are required" });
  }

  const newId = Date.now();
  const newUser: User = { id: newId, name, email };
  users.push(newUser);

  res.status(201).json(newUser);
});

Key Points About POST

  1. Data comes in req.body - The express.json() middleware parses JSON data
  2. Generate unique IDs - In a real app, the database would do this automatically
  3. Return 201 Created - Standard status code for successful creation
  4. Return the created resource - Include the new ID in the response

Test this with Postman or from the frontend.



Repo link

Tags: