繁体   English   中英

如何为 index.html 以外的网页运行/查看 ExpressJS 服务器?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM