Node js Web application Development Part 3

Supun Dharmarathne
technodyne
Published in
3 min readDec 27, 2013

Here is the sourcecode for the project : https://github.com/supun/NodeExpress

Writing to the database is not particularly difficult. Essentially we need to set up a route that takes a POST, rather than a GET. We could use AJAX here, and honestly that’s my preference most of the time … but that’s really a whole different tutorial, so we’ll stick to a standard post-and-show-results approach. Once again, though, it’s not too hard to adapt things to work that way if you want.

STEP 1 — CREATE YOUR DATA INPUT

We’re going quick and dirty here: two ugly, unstyled text inputs and a submit button. 1996-style. Just like before, we’ll start with app.get(); and then give it something to get. Open up app.js and find the part with all of those app.get() calls, and add this to the bottom of them:

[sourcecode language=”js”]
app.get(‘/newuser’, routes.newuser);
[/sourcecode]

So that you get:

[sourcecode language=”js”]
app.get(‘/’, routes.index);
app.get(‘/users’, user.list);
app.get(‘/helloworld’, routes.helloworld);
app.get(‘/userlist’, routes.userlist(db));

// New Code
app.get(‘/newuser’, routes.newuser);
[/sourcecode]

As with all app.get requests, we need to adjust the route to know what to serve up. Open up /routes/index.js and add the following:

[sourcecode language=”js”]
exports.newuser = function(req, res){
res.render(‘newuser’, { title: ‘Add New User’ });
};
[/sourcecode]

Now we just need a template, as newuser.jade, and replace the whole file contents with this:

[sourcecode language=”js”]
extends layout

block content
h1= title
form#formAddUser(name=”adduser”,method=”post”,action=”/adduser”)
input#inputUserName(type=”text”, placeholder=”username”, name=”username”)
input#inputUserEmail(type=”text”, placeholder=”useremail”, name=”useremail”)
button#btnSubmit(type=”submit”) submit
[/sourcecode]

Here we’re creating a form with the ID “formAddUser” (I like to preface my IDs with the type of thing we’re ID’ing. It’s a personal quirk). Method is post, action is adduser. Pretty straightforward. Under that we’ve defined our two inputs and our button.

If you restart your node server and go to http://localhost:3000/newuser you’ll see your form in all its glory.

browsershot4

Go ahead and submit. Enjoy the “can’t post to /adduser” error. We’re about to fix that.

STEP 2 — CREATE YOUR DB FUNCTIONS

OK, same process as before. First we edit app.js, then our route file, and then our Jade template. Except there’s no Jade template here because we’re posting and then forwarding. See below. It’ll all make sense! Let’s start: Open app.js and once again find your stack of app.get calls:

Now add the following at the bottom of the app.js:

[sourcecode language=”js”]

app.post(‘/adduser’, routes.adduser(db));

[/sourcecode]

Note that that’s an app.post, not an app.get. If you want to separate it from the app.gets with a comment or newline, I won’t stop you. Let’s set up our route.

Go back to /routes/index.js and let’s create our insertion function. This is a big one, so I’ve commented the code pretty thoroughly. Here it is:

[sourcecode language=”js”]
exports.adduser = function(db) {
return function(req, res) {

// Get our form values. These rely on the “name” attributes
var userName = req.body.username;
var userEmail = req.body.useremail;

// Set our collection
var collection = db.get(‘usercollection’);

// Submit to the DB
collection.insert({
“username” : userName,
“email” : userEmail
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send(“There was a problem adding the information to the database.”);
}
else {
// If it worked, set the header so the address bar doesn’t still say /adduser
res.location(“userlist”);
// And forward to success page
res.redirect(“userlist”);
}
});

}
}
[/sourcecode]

Assuming your server is running, which it should be, return to your web browser and point it at http://localhost:3000/newuser again. There’s our exciting form, just like before. Except now let’s fill in some values before we hit submit. I went with username “noderocks” and email “noderocks@rockingnode.com” … you can go with whatever you’d like.

browsershot5

It will redirect to userslist.

browsershot6

Reference : http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/

--

--