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.
// 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().
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.