简体   繁体   中英

Node.js, MongoDB Login form

I have a node.js application with a connection to a remote mongoDB server. The database contains some custom codes that have been pre-created and distributed to certain users. The idea is that only those who enter one of such codes into a form on the index page can be allowed to view the rest of the site. That is, I want to cross-reference the code entered with the master list stored in my database.

This is an example of what I'm trying to do(note this is in 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;
});

The above code is within a router.post('/', function(req, res){...}) function.

My question is, how do I clear the text input area(without refreshing the page) and ask the user to re-enter a new code when a wrong code is entered?

Secondly how do I redirect the user to a new page on valid entry of a code? Thanks.

  1. For that kind of behavior you would need to submit the form via XHR, parse the (JSON) response, and then clear the form on error and display error information. On the server side you can simply do something like res.json({ status: 'success' }); or res.json({ status: 'error', error: 'Bad token' });

  2. On success, you could do the redirect in the browser via window.location.replace("http://example.org/foo"); or if you want the current page in the session history (eg reachable with the browser's back button) you can use window.location.href = "http://example.org/foo" .

  1. To clear the input: I would handle this on the front-end, so that everytime the button is clicked (to send the form) it clears the input with:

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

Then in your script:

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

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

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

2. To redirect the user to a new page

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

You can do the following in your routes to redirect user to the home route.

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

    if err throw err 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM