Node.js,MongoDB登录表单

Node.js, MongoDB Login form

本文关键字:登录 表单 MongoDB js Node      更新时间:2023-09-26

我有一个node.js应用程序,它连接到远程mongoDB服务器。该数据库包含一些预先创建并分发给某些用户的自定义代码。其想法是,只有那些在索引页面上的表单中输入其中一个代码的人才能查看网站的其余部分。也就是说,我想将输入的代码与存储在我的数据库中的主列表进行交叉引用。

这是我尝试做的一个例子(注意这是在routes/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('/',function(req,res){…})作用

我的问题是,当输入错误的代码时,如何清除文本输入区域(而不刷新页面)并要求用户重新输入新代码?

第二,如何在有效输入代码后将用户重定向到新页面?谢谢

  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"

  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('/');
    }
})