Submit a form in post method in Node.js

<!DOCTYPE html>
<html lang=”en”>
<head>
  <meta charset=”UTF-8″>
  <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
  <title>Form Submission</title>
</head>
<body>
  <h1>Submit Form</h1>
  <form action=”/submit” method=”POST”>
    <label for=”name”>Name:</label>
    <input type=”text” id=”name” name=”name” required><br><br>
    <label for=”email”>Email:</label>
    <input type=”email” id=”email” name=”email” required><br><br>
    <button type=”submit”>Submit</button>
  </form>
</body>
</html>
const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const path = require(‘path’);
const app = express();
// Middleware to parse the form data
app.use(bodyParser.urlencoded({ extended: true }));
// Serve HTML form on the root URL
app.get(‘/’, (req, res) => {
  res.sendFile(path.join(__dirname, ‘index.html’));
});
// Handle POST request when the form is submitted
app.post(‘/submit’, (req, res) => {
  const formData = req.body;
  console.log(‘Form data received:’, formData);
  // Respond with a simple success message
  res.send(‘Form submitted successfully’);
});
// Start the server
app.listen(3000, () => {
  console.log(‘Server is running on http://localhost:3000’);
});

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top