[英]How to run/view ExpressJS server for webpages other than index.html?
所以,我想從我的公共文件夾中查看/運行/顯示除 index.html 以外的網頁,該文件夾有多個使用 ExpressJS 和 NodeJS 的 html 文件。 每次運行我的服務器,我只能查看 index.html 文件。 有沒有辦法可以訪問其他 html 文件? 我是初學者,剛剛開始使用后端部分。 這是我的 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);
});
我的公共文件夾
Public
-index.html
-createelection.html
-voterlogin.html
從對該問題的評論中:
localhost:3000/createelection
默認情況下,static 模塊將:
/
結尾的路徑,請給您index.html
您要求createelection
但文件名為createelection.html
。
使用您當前的代碼,您需要詢問http://localhost:3000/createelection.html
。
或者,您可以告訴 Express 嘗試為您自動完成文件擴展名。 查看static 模塊的文檔:
extensions :設置文件擴展名后備:如果找不到文件,則搜索具有指定擴展名的文件並提供第一個找到的文件。 示例:
['html', 'htm']
。
該設置默認為false
所以你需要:
app.use(express.static(static_path, { extensions: true }));
您可以使用routes
。 路由允許您在瀏覽器中輸入路徑,快速服務器將處理請求和 output 您的文件,而不必輸入絕對路徑。
例子:
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);
});
運行上面的代碼后,如果你在瀏覽器中輸入localhost:3000
,就會顯示你的index.html
文件,如果你輸入localhost:3000/create-electron
你會看到createelectron.html
等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.