0
0
Expressframework~5 mins

POST route handling in Express

Choose your learning style9 modes available
Introduction

POST route handling lets your server receive and process data sent by users or other programs. It helps your app accept information like form entries or JSON data.

When a user submits a form on a website, like signing up or logging in.
When an app sends data to the server to create a new record, like adding a comment.
When uploading files or images to the server.
When an API client sends data to update or create resources.
When you want to keep data private and not show it in the URL.
Syntax
Express
app.post('/route', (req, res) => {
  // handle data from req.body
  res.send('response');
});

The app.post method defines a route that listens for POST requests.

Data sent by the client is accessed via req.body, so you need middleware like express.json() to parse JSON data.

Examples
This example reads a name from the POST data and sends a greeting back.
Express
app.post('/submit', (req, res) => {
  const name = req.body.name;
  res.send(`Hello, ${name}!`);
});
This logs the received data and sends a 201 status code to confirm creation.
Express
app.post('/data', (req, res) => {
  console.log(req.body);
  res.status(201).send('Data received');
});
Sample Program

This Express app listens on port 3000. It uses express.json() to read JSON data sent in POST requests. The /user route expects a JSON body with username and age. It sends back a message with that info or an error if missing.

Express
import express from 'express';

const app = express();
const port = 3000;

// Middleware to parse JSON body
app.use(express.json());

// POST route to receive user info
app.post('/user', (req, res) => {
  const { username, age } = req.body;
  if (!username || !age) {
    return res.status(400).send('Missing username or age');
  }
  res.send(`User ${username} is ${age} years old.`);
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
OutputSuccess
Important Notes

Always use express.json() middleware to parse JSON POST data.

Check for required fields in req.body to avoid errors.

Use appropriate HTTP status codes like 400 for bad requests and 201 for successful creation.

Summary

POST routes let your server accept data sent by clients.

Use app.post with a path and a function to handle the data.

Access sent data via req.body after adding JSON parsing middleware.