Thuta Learning
ProjectsWeb Developmentbeginner

POST New Item

Relax. We'll talk through this in plain words — no textbook voice.

POST requests are used when you want to add new data to the server — things like registering a new user, adding a new product, or submitting a contact form.

javascript
// Add this middleware before routes
app.use(express.json());

app.post('/api/users', (req, res) => {
  const name = req.body.name;

  if (!name || name.trim() === '') {
    return res.status(400).json({
      message: 'Name is required'
    });
  }

  const newUser = {
    id: users.length + 1,
    name: name.trim()
  };

  users.push(newUser);

  res.status(201).json({
    message: 'User created successfully',
    data: newUser
  });
});

req.body.name reads the name from the JSON body the client sent. If name is missing, it returns a 400 Bad Request. If it's valid, a new user object is built and added to the array with users.push().

You should see
POST /api/users Body: { "name": "Kyaw Kyaw" } { "message": "User created successfully", "data": { "id": 3, "name": "Kyaw Kyaw" } }

Info

When creation succeeds, it's more correct to use a 201 status code. When validation fails, returning 400 makes it easier for the frontend to understand the error.

Easy traps

  • If the client is sending JSON, the Content-Type: application/json header should be set — otherwise you may run into body parsing issues.

Exercise

Build things like contact forms, signup forms, order creation, booking requests, and feedback submissions using POST endpoints.

You'll know it worked when:

POST New Item | Thuta Learning