You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重定向至带参数URL后Pug模板无法渲染求助

问题:带参数的URL重定向后Pug模板无法渲染

当重定向到带参数的URL(如/profile/用户名)时,对应的Pug模板无法渲染;但移除参数直接访问/profile时页面能正常显示。需求是用户登录后通过/profile/login提交数据,校验成功后重定向到带用户名的个人资料页,从数据库拉取信息填充模板,目前报错无法读取user.username,但实际数据库能找到对应用户。

相关代码

登录校验与个人资料函数

exports.loginCheck = async (req, res) => {
    let usernameStr = req.body.username;
    let passwordStr = req.body.password;

    var userFound =  await User.findOne()
    .where("username")
    .equals(usernameStr)
    .where("password")
    .equals(passwordStr)
    .select("username email age password answer1 answer2 answer3")
    .then((account) => {
        console.log(userFound);        
        res.redirect(`/profile/${account.username}`);
        
    })
    .catch((err) => {
        console.log(err);
        res.render("login", {
            errorMsg: 'Username and/or password is incorrect.'
            
        });
    });
}

exports.profile = async (req, res) => {
    var param = req.params.userP;

    var userFound =  await User.findOne()
    .where("username")
    .equals(param)
    .select("username email")
    .then((user) => {
        res.render('profile', {
            username: user.username, // 报错:无法读取'.username',但实际能找到用户
            email: user.email
        })
    })
}

路由配置

app.get('/profile/:userP', routes.profile); // 带参数的路由无法渲染模板
app.get('/profile', routes.profile); // 无参数的路由可以正常渲染
app.post('/profile/login', urlencodedParser, routes.loginCheck); // 登录提交的POST路由

问题分析与解决方案

1. 修复loginCheck函数的异步混用问题

你同时使用了await和.then()链式调用,这会导致变量userFound值异常,.then()里的console.log(userFound)会输出undefined。统一用try/catch处理异步逻辑:

exports.loginCheck = async (req, res) => {
    try {
        const usernameStr = req.body.username;
        const passwordStr = req.body.password;

        // 直接用await获取查询结果,无需链式.then()
        const account = await User.findOne()
            .where("username").equals(usernameStr)
            .where("password").equals(passwordStr)
            .select("username email age password answer1 answer2 answer3");

        if (!account) {
            // 未找到用户时直接渲染登录页提示错误
            return res.render("login", {
                errorMsg: 'Username and/or password is incorrect.'
            });
        }

        console.log(account);
        res.redirect(`/profile/${account.username}`);
    } catch (err) {
        console.log(err);
        res.render("login", {
            errorMsg: 'An error occurred during login.'
        });
    }
}

2. 修复profile函数的错误处理与异步混用

profile函数同样存在await和.then()混用问题,且未处理查询不到用户的场景,导致报错。修改如下:

exports.profile = async (req, res) => {
    try {
        const param = req.params.userP;
        const user = await User.findOne()
            .where("username").equals(param)
            .select("username email");

        if (!user) {
            // 未找到用户时返回404或跳转至登录页
            return res.status(404).send("User not found");
            // 或者跳转回登录页:return res.redirect("/login");
        }

        res.render('profile', {
            username: user.username,
            email: user.email
        });
    } catch (err) {
        console.log(err);
        res.status(500).send("Server error");
    }
}

3. 验证路由参数传递

确保重定向后的URL参数正确,比如用户名为testuser时,重定向地址应为/profile/testuser,此时req.params.userP会正确获取到testuser,查询数据库就能拿到对应用户数据,模板即可正常渲染。

内容的提问来源于stack exchange,提问作者Priest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 20:22:29