Node JS Rest App Contd.

This the part 2 of the post for creating a simple REST app in Node.js. Please click here for the previous post

Step 1 : Create router for REST.

Create file named rest.js under folder “routes”. The code app.use('/rest',rest); is used to route all the /rest request to this js file.

Step 2 : Declarations

var express = require('express');
var router = express.Router();
var events = require('events');

Above declarations are making  the express module and events module. We also get the router from the express app.

Step 3 :

Now we create a sample page that acts a home page for our rest app.

So the route for that is

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express Rest' });
next();
});

Also we need to create a file index.jade under the folder views.


block content
h1= title
p Welcome to #{title}

type http://localhost/rest to see the result.

Step 4 : GET function


router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.json(docs);
});
});

In above code .get is the HTTP method GET and it gets the list of all users from DB.

router.get('/user/:username', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({'username':req.params.username},{},function(e,docs){
res.json(docs);
});
});

Above code is an example of getting the user based on user name.
Step 5 : POST function

Below is an example for implementation of POST http method. Here req.body is saved as it is in DB. We cal also access the parameters by req.body.{param}

/* POST to Add User Service */
router.post('/user', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Set our collection
var collection = db.get('usercollection');
// Submit to the DB
collection.insert(req.body, function (err, doc) {
if (err) {
// If it failed, return error
res.json({status : 1 , message : "There was a problem adding the information to the database."});
} else {
res.json({status : 0 ,message : "User Created"});
}
});
});

 

Step 6

The last line should be the following

module.exports = router;

 

The code is in github

Leave a Reply

Your email address will not be published. Required fields are marked *