2014-10-03 106 views
0

我有一個連接到遠程mongoDB服務器的nod​​e.js應用程序。該數據庫包含一些已經預先創建並分發給某些用戶的自定義代碼。這個想法是,只有那些在索引頁面上輸入這樣的代碼之一才能被允許查看網站的其餘部分。也就是說,我想交叉引用輸入的代碼與存儲在我的數據庫中的主列表。Node.js,MongoDB登錄表

這是我想要做的一個例子(注意,這是在路由/ index.js):

collection.findOne({ "Code": "fooCode" }, function(err, doc){ 
    if you cannot find fooCode 
     show an error message, clear the input area and tell the user to re-enter a correct code 

    if you find fooCode 
     redirect to a new page; 
}); 

上面的代碼是一個 router.post內(「/」,函數(req,res){...}) 函數。

我的問題是,如何清除文本輸入區域(無需刷新頁面)並要求用戶在輸入錯誤代碼時重新輸入新代碼?

其次,我如何將用戶重定向到有效輸入代碼的新頁面?謝謝。

+0

你爲什麼不嘗試做一個ajax調用?你在前端使用什麼客戶端? – 2014-10-03 21:42:04

回答

0
  1. 對於這種行爲,您需要通過XHR提交表單,解析(JSON)響應,然後清除錯誤表單並顯示錯誤信息。在服務器端,你可以簡單地這樣做res.json({ status: 'success' });res.json({ status: 'error', error: 'Bad token' });

  2. 成功時,你可以通過window.location.replace("http://example.org/foo");做瀏覽器重定向,或者如果你想在會話歷史記錄當前頁面(例如,您可利用瀏覽器的後退按鈕)你可以使用window.location.href = "http://example.org/foo"

0
  1. 清除輸入:我會處理這個問題上的前端,從而使每次的按鍵(發送表單),它會清除輸入有:

    <input id="userInput" type="text"> <button id="submitBtn">Send</button>

然後在你的腳本:

// Cache DOM 
const myInput = document.getElementById('userInput'); 
const myBtn = document.getElementById('submitBtn'); 

// Event Bind 
myBtn.on('click', clearInput); 

// Functions 
function clearInput() { 
    myInput.value = '';  
} 

2.將用戶重定向到新的一頁

res.redirect('/<path>'); 

你可以在你的路由的以下用戶重定向到回家的路線。

collection.findOne({ "Code": "fooCode" }, function(err, doc){ 

    if err throw err 

    else {  
     res.redirect('/'); 
    } 
})