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 }));
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.