0
0
ExpressHow-ToBeginner · 3 min read

How to Use app.post in Express: Simple Guide with Examples

Use app.post(path, callback) in Express to handle HTTP POST requests sent to the specified path. The callback function receives the request and response objects to process data and send a response.
📐

Syntax

The app.post method defines a route that listens for HTTP POST requests on a given path. It takes two main parts:

  • path: The URL path where the POST request is handled.
  • callback: A function with req (request) and res (response) parameters to process the request and send back a response.
javascript
app.post(path, (req, res) => {
  // handle POST request
  res.send('Response message');
});
💻

Example

This example shows how to create a simple Express server that listens for POST requests at /submit. It reads JSON data sent by the client and responds with a confirmation message.

javascript
import express from 'express';

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

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

app.post('/submit', (req, res) => {
  const data = req.body;
  res.send(`Received your data: ${JSON.stringify(data)}`);
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
Output
Server running on http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when using app.post include:

  • Not using middleware like express.json() to parse JSON request bodies, causing req.body to be undefined.
  • Forgetting to send a response, which leaves the client hanging.
  • Using the wrong HTTP method (e.g., app.get instead of app.post) for POST requests.
javascript
/* Wrong: Missing JSON parser middleware */
app.post('/data', (req, res) => {
  console.log(req.body); // undefined
  res.send('Done');
});

/* Right: Add JSON parser middleware */
app.use(express.json());
app.post('/data', (req, res) => {
  console.log(req.body); // parsed JSON
  res.send('Done');
});
📊

Quick Reference

  • app.post(path, callback): Handles POST requests at path.
  • req.body: Contains parsed data sent by the client (requires middleware).
  • res.send(): Sends a response back to the client.
  • Always use express.json() middleware to parse JSON bodies.

Key Takeaways

Use app.post(path, callback) to handle HTTP POST requests in Express.
Include express.json() middleware to parse JSON request bodies before accessing req.body.
Always send a response inside the callback to avoid hanging requests.
app.post routes only respond to POST requests, not GET or others.
The callback function receives req and res objects to handle request data and send responses.