fireblade
Posts: 4
Joined: Wed Jan 14, 2015 10:07 pm

Node.js prevent form submit to clear and redirect

Wed Dec 23, 2015 7:10 pm

I'm developing a web app in node.js to register users in a database and I have a doubt.
In the server side in the node.js Post handling (after submit a registration html form), I need to check if the username existes in database. If the username doesn't existe, the program continues and redirects to another page, but if the username existes I need that the program sends an alert to html page, doesn't clean the form and prevents to redirects to another page.
For example:

Code: Select all

app.post('/register', function(req, res) {
		if username doesn't existe (check that previously on database)
			res.redirect('/users');
		else
			send alert to html page, prevent to clear form, prevent to redirect
}
I need to know how I can send variables from server to html client, prevent to clear form and prevent the post redirect.

Thanks

Heater
Posts: 16092
Joined: Tue Jul 17, 2012 3:02 pm

Re: Node.js prevent form submit to clear and redirect

Thu Dec 24, 2015 12:55 am

I have recently been experimenting with such login and registration pages and node.js. Here is what I do on the server for registration:

Code: Select all

router.post('/api/register', function (req, res) {
    var account = {
        username:  req.body.username,
        email:     req.body.email,
        password:  req.body.password,
        givenName: 'unkown',
        surname:   'unkown',
        customData: {
            favoriteColor: 'white',
        }
    };
    stormpathApp.createAccount(account, function(err, account) {
        if (err) {
            console.log('stormpath account creation failed', err);
            res.status(418).send(err.message); // I'm a tea pot
        } else {
            res.status(200).send({});
        }
    });
});
The "register" post request get's username, email and password from the registration form in req.body.

It then tries to create that account using the free Stormpath authentication service (stormpath.com). If that fails with an err, could be an existing user name etc, then I return an HTML error code (418) along with an error message text in the response body. The client simply displays that error message at the bottom of the registration form, keeping all the fields unchanged.

If the registration succeeds then a 200 is returned and an empty object for the response body which is ignored by the client. The client then displays a "Signup OK" message. The client should then transition to another page but I have not got that far yet.

Of course this relies on some JS in the registration page. When the user hits the submit button on the registration page this is run:

Code: Select all

 
 handleSubmit (event) {
     event.preventDefault();

     const username  = this.refs.username.getValue();
     const email     = this.refs.email.getValue();
     const password1 = this.refs.password1.getValue();
     const password2 = this.refs.password2.getValue();

     if (password1 !== password2) {
         this.setState({ error: true, message: 'Entered passwords do not match'});
         return;
     }
     request
         .post('/api/register')
         .send({ username: username, email: email, password: password1 })
         .set('X-API-Key', 'foobar')
         .set('Accept', 'application/json')
         .end(function (err, res) {
             // Calling the end function will send the request
             console.log('--------------------------------------------------------');
             if (err) {
                 console.log('Registration request FAIL');
                 this.setState({ error: true, message: 'Signup failed: User name already in use' });
                 return;
             }
             console.log('Registration request OK');
             console.log('--------------------------------------------------------');
             this.setState({ error: false, message: 'Signup OK.'});
         }.bind(this));
 }
This is using react.js which you may not be familiar with but you can see that on submit a post request is made sending username, email and password. When the response comes back a success or failure message is inserted into the page under the form. Again, on success this JS should do something other than sit on the same page but I have not got there yet.

I have this running on a server here: https://xn--2-umb.net
and all the source code, client and server, is here: https://bitbucket.org/zicog/propanel

Have a look in server/index.jsx and app/components/signup.jsx

Note: This is a work in progress, probably is not secure, definitely lacking features.
Memory in C++ is a leaky abstraction .

Heater
Posts: 16092
Joined: Tue Jul 17, 2012 3:02 pm

Re: Node.js prevent form submit to clear and redirect

Thu Dec 24, 2015 1:27 am

...if the username existes I need that the program sends an alert to html page, doesn't clean the form and prevents to redirects to another page.
Hmm...been thinking...

Seems to me that if you are not using Javascript in the page then the only thing to do is for the server to respond to the "register" post request with the same registration page again but this time with the username/password/whatever fields filled in with the user data it has just been sent in the request. Along with whatever error message you want inserted somewhere.
Memory in C++ is a leaky abstraction .

Return to “Other programming languages”