如何在客户端调用flash?

How to call flash on the client-side?

代码:

login.ejs

<script>
    req.flash('success_msg', 'You have logged in');
</script>

header.ejs

<div class = "alertMessage">

    <% if (success_msg != false){ %>
        <span class="alert alert-success containerMargins">
            <%= success_msg %>
        </span>
    <% } %>
    <% if (error_msg != false){ %>
        <span class="alert alert-danger containerMargins">
            <%= error_msg %>
         </span>
    <% } %>

    </div>

情况:

这与在服务器端使用 flash 并在客户端显示消息无关:它已经非常适合我。

这与从客户端调用 flash 或使用其他库从客户端复制相同的行为有关。


问题:

我展示的代码当然不能在客户端运行,我可以做些什么来在客户端复制该行为?

The flash is a special area of the session used for storing messages. Messages are written to the flash and cleared after being displayed to the user. The flash is typically used in combination with redirects, ensuring that the message is available to the next page that is to be rendered.

所以你需要代码:

  1. 将一些数据存储在客户端可以在页面之间访问的地方
  2. 读取该数据
  3. 读取后删除

首先选择 for option 1 (such as localStorage, or a cookie). The rest should be trivial - the original module is about 80 lines of code, including about 50% comments — 实施(但具体取决于您做出的选择)。

这是我使用的解决方案:

<div class = "alertMessage">

    <span class="alert alert-success containerMargins" id="successDiv"></span>

    <span class="alert alert-danger containerMargins" id="errorDiv"></span>

</div> 

<script>

        if (localStorage.getItem("success_msg_local") != null) {
            document.getElementById("successDiv").innerText = localStorage.getItem("success_msg_local");
            document.getElementById("successDiv").style.display = "inline-block";
            window.localStorage.clear();
        }
        else if (localStorage.getItem("error_msg_local") != null) {
            document.getElementById("errorDiv").innerText = localStorage.getItem("error_msg_local");
            document.getElementById("errorDiv").style.display = "inline-block";
            window.localStorage.clear();
        }

</script>

并将 req.flash('success_msg_local', 'You have logged in') 替换为:

localStorage.setItem('success_msg_local', 'You have logged in');