Thursday, 19 December 2024

Node.js with create server using Express with middleware function



Express using create server.

const express = require('express');
const app = express();

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

// Custom Middleware to Modify Request Data
app.use((req, res, next) => {
  if (req.body && typeof req.body === 'object') {
    // Add a new property to the request body
    req.body.modified = true;

    // Log the modified request body
    console.log('Modified Request Data:', req.body);
  }
  next(); // Pass control to the next middleware/route handler
});

// Example Route to Test Middleware
app.post('/data', (req, res) => {
  res.send({
    message: 'Request received successfully!',
    requestData: req.body,
  });
});

// Start the Server
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

No comments:

Post a Comment