【问题标题】:res.location is not setting page url in express (MEAN stack)res.location 没有在 express 中设置页面 url(MEAN 堆栈)
【发布时间】:2026-01-03 16:40:01
【问题描述】:

我需要一个硬编码的密码保护页面。我使用 href 以 /admin/user/password 的身份重定向到页面:

    <a ng-href="/admin/{{user}}/{{password}}" class="form-control btn btn-primary" >Submit</a>

我使用 angular $scope.user 和 $scope.password 作为输入字段的 ng 模型。此请求被 Express route.get 函数捕获:

    app.route('/admin/:user/:password')
     .get(admin.renderAdmin);

下面是我的 admin.renderAdmin 页面:

exports.renderAdmin = function (req, res) {
console.log("Requested with username and password");

if (req.params.user === "*******" && req.params.password === "******") {

    res.location('/admin');
    res.render('admin');

} else {
    res.send(null);
}
};

/admin 是我需要的 url,admin.ejs 存储我想在这个 url 上呈现的 html。

我得到的输出是页面呈现 admin.ejs 但 url 没有改变,它与 href 相同。

请帮助我解决我在这里可能做错的事情。提前致谢。

【问题讨论】:

    标签: javascript node.js express routing mean-stack


    【解决方案1】:

    也许尝试使用回调进行渲染?

    // if a callback is specified, the rendered HTML string has to be sent explicitly
    res.render('admin', function(err, html) {
      res.location('/admin');
      res.send(html);
    });
    

    此外,如果您希望页面实际发生变化,则应使用 res.redirect() 而不是 res.location()

    【讨论】:

      最近更新 更多