簡體   English   中英

如何在快速通道上重新顯示頁面並顯示錯誤消息?

[英]How can I re-render a page on an express-route with an error message?

我正在開發一個簡單的網站,該網站基於帶有用戶列表和哈希密碼的本地JSON文件,支持登錄和注銷功能。 我正在使用cookie的express-session來跟蹤用戶是否在服務器端成功登錄並表示為服務器。

在登錄頁面上,呈現login.handlebars視圖。 如果用戶使用匹配的憑據成功登錄,頁面將重新路由到/ private。 當前,如果用戶未輸入匹配的登錄憑據,頁面將刷新。

如果用戶嘗試使用不正確的憑據登錄,則需要重新渲染/刷新同一頁面,僅這次是使用401狀態代碼,並在頁面上顯示錯誤消息。

這是我到目前為止在服務器端的登錄路徑中的內容:

router.get("/", async (req, res) => {
    res.render("login/login")
})

router.post("/", async (req, res) => {
    // Check if user name is in users
    for(let i=0; i < users.length; i++){

        // If the user name is valid and found in the data base
        if(users[i].username === req.body.username){
            // Compare the passwords of the user to the hashedPassword that is stored
            let hashcmp = await bcrypt.compare(req.body.password, users[i].hashedPassword)

            if(hashcmp){
                // Set the cookie and authenticate the login
                console.log("Correct user name and password, setting AuthCookie")
                req.session.userId = String(users[i]._id)
                req.session.loggedin = true
                // Redirect to private
                res.redirect("/private")
                return
            }
            // If the passwords dont match --> break the loop
            else{
                break
            }
        }
    }

    // Otherwise redirect to get /login
    // TODO: Re-render page with error message and 401 status code
    res.redirect("/login")
    return
})

實現此目標的最佳/最理想的解決方案是什么? 如果另外需要重新渲染登錄頁面,那么在實際操作中如何使用登錄頁面完成此操作?

您可以使用connect-flash 它是Express的Flash消息中間件。 我建議您閱讀一些有關此的內容。

閃存是會話中用於存儲消息的特殊區域。 消息被寫入閃存,並在顯示給用戶后清除。 Flash通常與重定向結合使用,以確保該消息可用於將要呈現的下一頁。

首先,在您的app.js文件中,要求該模塊const flash = require('connect-flash');
然后,在同一文件中,在您的路線定義之前,添加以下代碼

app.use(flash());

// Add errors on locals.
app.use(function (req, res, next) {
  res.locals.errors = req.flash("error");
  next();
});

res.locals是一個對象,其中包含可用於下一個渲染視圖的響應局部變量。
接下來,在您的控制器中,在res.redirect("/login") ,將錯誤消息添加到locals對象中。

// Otherwise redirect to get /login
// TODO: Re-render page with error message and 401 status code
req.flash("error", "User does not exist.");
res.redirect("/login")

最后要做的是在登錄視圖中添加errors 我不確定車把,但是在ejs文件中我使用以下代碼:

<div>
<% errors.forEach(function (error) { %>
    <p><%= error %></p>       
<% }) %>
</div>

也許在車把里你可以使用這樣的東西

<div>
  {{#each errors}}
    <p>{{this}}</p>
  {{/each}}
</div>

同樣,您應該閱讀connect-flash工作原理以及該模塊的功能。 這對於不同類型的消息非常有用,不僅是錯誤消息。

這很簡單。 只需使用res.render通過傳遞錯誤消息來呈現所需的頁面

// Otherwise redirect to get /login
// TODO: Re-render page with error message and 401 status code
res.status(401).render("login/login", { error: "Opps!" })
return

您認為有條件的:

<div class="error">
  {{#if error}}
    <p>{{error}}</p>
  {{/if}}
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM