So, I want to view/run/display webpages other than the index.html from my public folder which has multiple html files using ExpressJS and NodeJS. Every time I run my server, I can only view the index.html file. Is there a way I can access other html files? I am a beginner and just getting started with the backend part. This is my app.js
app=express();
const path=require('path');
const Router=express.Router();
const port=process.env.PORT||3000;
require("./db/connectdb");
const static_path=path.join(__dirname,"../../frontend/public");
app.use(express.static(static_path));
app.get('/createelection',(req,res)=>{
console.log("Create an Election here");
});
app.listen(port,()=>{
console.log('Server is running at port no. ' port);
});
My Public Folder
Public
-index.html
-createelection.html
-voterlogin.html
CodePudding user response:
You can use routes
. Routes allow you to enter a path in the browser and the express server will handle the request and output your file, instead of having to enter an absolute path.
Example:
const express = require("express");
const app = express();
const path = require("path");
const port = process.env.PORT || 3000;
require("./db/connectdb"); // Connect to the database
// Define a static path
const static_path = path.join(__dirname, "../../frontend/public");
// Send all static files to the server
app.use(express.static(static_path));
// Routes
app.get("/", (req,res) => {
res.sendFile(path.join(static_path, "/index.html");
});
app.get("/create-electron", (req,res) => {
res.sendFile(path.join(static_path, "/createelectron.html");
});
app.get("/login", (req,res) => {
res.sendFile(path.join(static_path, "/voterlogin.html");
});
// Run app on a specific port
app.listen(port,() => {
console.log("Server is running at port no. " port);
});
After running the code above, if you enter localhost:3000
into your browser, your index.html
file will be displayed, if you enter localhost:3000/create-electron
you will see createelectron.html
, etc.