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
From a comment on the question:
localhost:3000/createelection
By default the static module will:
index.html if you ask for a path ending in /You are asking for createelection but the file is named createelection.html.
With your current code you need to ask for http://localhost:3000/createelection.html.
Alternatively you can tell Express to try to autocomplete the file extension for you. Look at the documentation for the static module:
extensions: Sets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example:
['html', 'htm'].
The setting defaults to false
So you would need:
app.use(express.static(static_path, { extensions: true }));