Render html file
Create and render HTML files
home.html
<h1>Home Page</h1>
<a href="login">Go to Login Page</a>
login.html
<h1>Login Page</h1>
<a href="/">Go to Home Page</a>
about.html
<h1>About Page</h1>
<a href="/">Go to Home Page</a>
Make node server with express js
import express from "express";
const app = express();
app.get("/", (req, resp) => {
resp.sendFile("view/home.html");
});
app.listen(3200);
resp.sendFile("view/home.html");
This gives you an error because you need an absolute path.
Get Absolute Path
Use the path
module to get absolute path.
import express from "express";
import path from "path";
const app = express();
app.get("/", (req, resp) => {
const absPath = path.resolve("view/home.html");
resp.sendFile(absPath);
});
app.get("/login", (req, resp) => {
const absPath = path.resolve("view/login.html");
resp.sendFile(absPath);
});
app.get("/about", (req, resp) => {
const absPath = path.resolve("view/about.html");
resp.sendFile(absPath);
});
app.listen(3200);
- We used
path.resolve()
to get the absolute path of HTML files.
Now you're ready to open the browser:
- Home →
http://localhost:3200/
- Login →
http://localhost:3200/login
- About →
http://localhost:3200/about