【问题标题】:nodejs redirect user with datanodejs用数据重定向用户
【发布时间】:2020-01-31 08:03:36
【问题描述】:

客户端将通过向我的服务器发送 POST 请求来登录。我的服务器会检查这个。如果可行,我想将欢迎页面发送给客户端,但通过模板引擎将一些数据插入其中。除了重定向部分,我什么都有。这就是我所拥有的(我使用把手作为模板引擎):

app.post("/loginAttempt",function(req, res)
{
    var username = req.body.username;
    var password = req.body.password;
        //if credentials are incorrect, data is false
        //otherwise, data is a html file as a string
        var data = await checkCredentials(username,password);
        if(data === false)
        {
            res.send("fail");
        }
        else
        {
            //not a real function, just using this to simplify code for this post
            var temp = compileWithHandlebars("./front-end/welcome.html",{myData: data});
            res.send(temp);
        }
});

这个问题是它发送一个 html 文件作为字符串而不是重定向。这意味着用户看不到 url 的变化,因此他们无法点击返回按钮返回登录页面。

【问题讨论】:

  • 你用res.render试过了吗?
  • 可以分享compileWithHandlebars方法的代码吗?
  • var temp = handlebars.compile(source)(templateData); ---------source是读取为字符串的html文件
  • 很难发布,因为它实际上是一个异步调用,所以我的真实代码在回调函数中有 res.send

标签: javascript node.js templates redirect


【解决方案1】:

我猜 temp 是一个字符串!

   app.post("/loginAttempt",function(req, res)
    {
        var username = req.body.username;
        var password = req.body.password;
            //if credentials are incorrect, data is false
            //otherwise, data is a html file as a string
            var data = await checkCredentials(username,password);
            if(data === false)
            {

                res.status(404).send("fail"); //<==
            }
            else
            {
                //not a real function, just using this to simplify code for this post
                //var temp = compileWithHandlebars("./front-end/welcome.html",{myData: data});


                res.redirect("./front-end/welcome.html",{data:myData});
            }
    });

【讨论】:

  • 这不起作用。客户端仍然将 html 文件作为字符串接收,而不是被重定向
猜你喜欢
  • 2022-12-17
  • 1970-01-01
  • 2013-09-07
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-28
相关资源
最近更新 更多