Route incoming request to an HTML file in Express JS

In this tutorial we gonna check how we can direct our incoming request to an html file. So here we gonna use express js’s res.sendFile to send the response as an HTML file.

As an example we are getting request to “/” for this we are responding a file called index.html

calculator.js

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

app.get("/", function(req, res){
   res.sendFile(__dirname + "/index.html");
});
app.listen(4000, function(){
    console.log("Server started at port 4000");
});

References:

dirname: How to get root directory path using Express JS Code

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="index.html"  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>

Output:

About the Author: smartcoder

You might like

Leave a Reply

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