【问题标题】:Send error message on redirect在重定向时发送错误消息
【发布时间】:2013-11-16 20:29:50
【问题描述】:

我有一个登录表单/login,它将登录信息发布到/checklogin。如果凭据不正确,我想将用户重定向到/login,并带有一条错误消息,类似于“用户名或密码不正确”。但是,我似乎无法弄清楚如何通过res.redirect 传递选项,就像您使用res.render 一样。

这样做的最佳方法是什么?我看到之前有人问过这个问题,但它似乎不适用于 Express 的更高版本。

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    仅使用重定向,实际上不可能传递查询字符串以外的选项:

    res.redirect('/login?e=' + encodeURIComponent('Incorrect username or password'));
    

    重定向指示客户端启动新请求,并且 HTTP 本身是无状态的。

    要保留消息,您需要一种持久性形式来为下一个请求保留它——cookie、会话等。

    req.session.error = 'Incorrect username or password';
    res.redirect('/login');
    

    然后:

    res.render('login', { error: req.session.error });
    delete res.session.error; // remove from further requests
    

    这也是 Express 2 的 req.flash() 帮助完成的。而且,它的一个变体仍可用于 Express 3 及更高版本——就像 connect-flash 而不是 being bundled

    【讨论】:

    • 在不能使用res.render的情况下?比如react-native app
    【解决方案2】:

    服务器端:

    res.redirect('/login?error=' + encodeURIComponent('Incorrect_Credential'));
    

    在视图中会有一个警报(希望你们正在使用引导程序)。但最初它将是隐藏的。如果出现错误,就会显示出来。

    <div class="alert alert-success" role="alert" id="loginAlert">
        <p style="text-align: center;">Incorrect Credential</p>
    </div>
    

    展示技巧:

    <script>
        $('#loginAlert').hide();
        const urlParams = new URLSearchParams(window.location.search);
        const myParam = urlParams.get('error');
        if(myParam == "Incorrect_Credential") {
            $('#loginAlert').show();
        }
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 2021-04-13
      • 2020-07-14
      • 2019-02-27
      • 1970-01-01
      相关资源
      最近更新 更多