Node.js: A Love Story

Recently a classmate, Steve Henningsgard, and I started working on a project in order to improve our web development knowledge. Specifically our knowledge of the MEAN stack, or MongoDB, Express, AngularJS, and Node.js. More in depth details of the project will be written about in a future blog post, so stay tuned.

This of course required the use of an API that would allow us to communicate with our database through various ways. Last night while attempting, and failing, to sleep I took the time to read about how API's are created and handled within Node. Thanks to the guys over at Scotch.io and their fantastic write ups about Node, the learning was painless. This morning I decided to try my hand at writing up an API implementation for our project between classes, and sure enough it was incredibly simple. Thank you Node!!

Here's the relevant code snippets for your perusing pleasure. These snippets simply go within a server.js file that's handling routing, or a separate routes.js file dedicated to routing, (my preferred method is the second).

GET request:

app.get('/api/posts', function(req, res) {
  Post.find(function(err, posts) {
    // if there is an error retrieving, send the error
    // nothing after res.send(err) will execute if there is one
    if (err) {
      res.send(err);
    }
    res.json(posts);
  });
});

POST request:

app.post('/api/posts', function(req, res) {
  var post = new Post();
  post.name = req.body.name;
  post.desc = req.body.desc;
  post.time = new Date();
  post.save(function(err) {
    if (err) {
      res.send(err);
    }
    res.json({ message: 'Post created!' });
  });
});

It's really that easy! Now this API can be easily tested from the Postman client, and you should see status messages within your console window that's running your Node server.

Hooray Node!!

comments powered by Disqus