Submit a form in post method in Node.js

install express and body-parser

sh
npm install express body-parser multer

server.js

const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const port = 3000;
app.use(bodyParser.urlencoded({ extended: true }));
// Serve HTML form
app.get("/", (req, res) => {
    res.send(`
        <form action="/submit" method="POST">
            <input type="text" name="name" placeholder="Enter your name" required />
            <button type="submit">Submit</button>
        </form>
    `);
});
// Handle form submission
app.post("/submit", (req, res) => {
    const { name } = req.body;
    res.send(`Hello, ${name}! Form submitted successfully.`);
});
// Start the server
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

 

 

Leave a Comment

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

Scroll to Top