Express.js 是否可以在多个目录而不是仅在 "views" 文件夹中呈现 EJS 页面?

Express.js is it possible to render EJS pages in multiple directories rather than only in the "views" folder?

所以我正在创建一个用户配置文件页面。用户可以登录到他们的帐户,然后被定向到他们独特的个人资料。我打算将格式设为:

www.MyDomainName.com/username/profile

现在我的问题是我的一些通用 public 页面位于 ejs 默认的“views”文件夹中,包括通用 login.ejs、registration.ejs、仪表板页面等。它们将在用户想要访问它们时呈现

但是,用户特有的页面(例如每个用户的个人资料页面)位于不同的目录下,以用户名命名。当用户成功验证后,这些页面也应该在用户想要访问它们时呈现。但是,当我 运行 本地主机中的服务器时,控制台告诉我这些页面必须位于 views 文件夹下

Error: Failed to lookup view "./username/profile" in views directory

所以我假设我必须将所有用户的文件放在 views 目录中才能显示它们,对吗?有什么解决方案可以避免这种情况吗?

初始化代码如下。我正在使用 MongoDB

const express = require("express");
const app = express();
const BodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");

app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(BodyParser.urlencoded({extended: true}));

// using Mongoose to create a User Database, that stores user id and password
userSchema = {username: String, password: String}
User = new mongoose.model("User", userSchema);

下面是将用户重定向到 profile.ejs

的实际功能
app.post("/login", function(req, res)
{
var username = req.body.username; // these are just the user entry fields in login.ejs
var password = req.body.password;

    User.findOne({username: username}, function(err, UserFound)
    {
        if (UserFound)
        {
            if (UserFound.password === password)
            {
                user_dir = "./" + username + "/profile"
                res.render(user_dir) // here I want to render the users' unique profile page
            }
            else
            {console.log("password incorrect")}
        }
        else
        {console.log("username incorrect")}
    })
});

如果您使用 ejs 库本身手动呈现文件,您可以对目录路径等内容进行更细粒度的控制。

例如,您的登录端点可能如下所示:

app.post("/login", function(req, res) {
    const {username, password} = req.body    
    User.findOne({username}, async function(err, UserFound) {
        if (UserFound && UserFound.password === password) {
            const profile = `./${username}/profile.ejs`
            const html = await ejs.renderFile(profile /*{data goes here if necessary}*/)
            res.send(html)                
        } else {
            console.log("username or password incorrect") // It is conventional to combine username / password incorrect warning to obfuscate this info from a potential attacker
        }
    })
});

完全不相关:看起来您在比较密码时没有先对它们进行哈希处理 - 您是否以明文形式存储密码?如果答案是“是”或“我不知道”,并且您打算在生产环境中使用此应用程序,请查看 password hashing