sample express app

// Step 1: Import required modules
const express = require('express');
const bodyParser = require('body-parser');

// Step 2: Create an Express application
const app = express();

// Step 3: Use middleware to parse JSON and URL-encoded bodies
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Step 4: Define a simple route
app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

// Step 5: Define a route with a parameter
app.get('/greet/:name', (req, res) => {
  const { name } = req.params;
  res.send(`Hello, ${name}!`);
});

// Step 6: Define a POST route to handle form submissions
app.post('/submit', (req, res) => {
  const { username, email } = req.body;
  res.send(`Submitted by ${username} with email ${email}`);
});

// Step 7: Set up the server to listen on port 3000
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Explanation:

  1. Import the required modules (express for the web framework and body-parser for parsing request bodies).

  2. Create an Express application by calling the express() function.

  3. Use middleware to parse incoming request bodies in JSON and URL-encoded formats.

  4. Define a simple route that responds with "Hello, Express!" when the root path ('/') is accessed using the HTTP GET method.

  5. Define a route with a parameter (/greet/:name) that responds with a personalized greeting based on the provided name parameter.

  6. Define a route to handle form submissions using the HTTP POST method. It extracts the username and email fields from the request body and sends a response.

  7. Set up the server to listen on port 3000. The server prints a message to the console when it starts.