How to handle POST request in Express JS

post_thumb

POST request can be received to the server and response can be given to that using express js.

eg:

app.post("/", function(req, res){
    res.send("Thanks for posting data!");
})

By clicking the calculate button, it will create a POST request to the backend. This request is handled in the backend express js code.

calculator.js

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

app.get("/", function(req, res){
   res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res){
    res.send("Thanks for posting data!");
});

app.listen(4000, function(){
    console.log("Server started at port 4000");
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <body>
        <h1> Calculator</h1>

        <form action="/"  method="post">
            <input type="text" name="num1" placeholder="First Number" />

            <input type="text" name="num2" placeholder="Second Number" />

            <button type="submit" name="submit">Calculate </button>



        </form>

    </body>
</head>
<body>
    
</body>
</html>

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published.