所以,我想查看/運行/顯示除 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
uj5u.com熱心網友回復:
從對這個問題的評論:
localhost:3000/createelection
默認情況下,靜態模塊將:
index.html如果您要求以 結尾的路徑,請給您/- 給你你要的檔案
您正在請求,createelection但檔案名為createelection.html.
使用您當前的代碼,您需要要求http://localhost:3000/createelection.html.
或者,您可以告訴 Express 嘗試為您自動完成檔案擴展名。查看靜態模塊的檔案:
extensions:設定檔案擴展名后備:如果未找到檔案,則搜索具有指定擴展名的檔案并提供第一個找到的檔案。例子:
['html', 'htm']。
設定默認為 false
所以你需要:
app.use(express.static(static_path, { extensions: true }));
uj5u.com熱心網友回復:
您可以使用routes. 路由允許您在瀏覽器中輸入路徑,快遞服務器將處理請求并輸出您的檔案,而不必輸入絕對路徑。
例子:
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等等。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/368414.html
標籤:javascript html 节点.js 表达 后端
