Microsoft Sql Server driver for Nodejs - Part 2

Posted by chanderdhall on ASP.net Weblogs See other posts from ASP.net Weblogs or by chanderdhall
Published on Tue, 19 Jun 2012 21:09:00 GMT Indexed on 2012/06/19 21:17 UTC
Read the original article Hit count: 370

Nodejs, Sql server and Json response with Rest

This post is part 2 of Microsoft Sql Server driver for Node js.In this post we will look at the JSON responses from the Microsoft Sql Server driver for Node js.

Pre-requisites:

  • If you have read the Part 1 of the series, you should be good.
  • We will be using a framework for Rest within Nodejs - Restify, but that would need no prior learning.

Restify:

Restify is a simple node module for building RESTful services. It is slimmer than Express. Express is a complete module that has all what you need to create a full-blown browser app. However, Restify does not have additional overhead of templating, rendering etc that would be needed if your app has views. So, as the name suggests it's an awesome framework for building RESTful services and is very light-weight.

Set up - You can continue with the same directory or project structure we had in the previous post, or can start a new one. Install restify using npm and you are good to go.

Go to Server.js and include Restify in your solution. Then create the server object using restify.CreateServer() - SLICK - ha?

Then make sure you provide a port for the Server to listen at. The call back function is optional but helps you for debugging purposes.

Once you are done, save the file and then go to the command prompt and hit 'node server.js' and you should see the following:

 Server Running

To test the server, go to your browser and type the address 'http://localhost:8080/' and oops you will see an error.

 Server error

Why is that? - Well because we haven't defined any routes. Let's go ahead and create a route. To begin with I'd like to return whatever is typed in the url after my name and the following code should do it.

You can also avoid writing call backs inline. Something like this.

Now if you go ahead and type http://localhost:8080/ChanderDhall/LovesNode you will get the response 'Chander Dhall loves node'.

NOTE: Make sure your url has the right case as it's case-sensitive. You could have also typed it in as 'server.get('/chanderdhall/:name', respond);'

Stored procedure:

We've talked a lot about Restify now, but keep in mind the post is about being able to use Sql server with Node and return JSON.

To see this in action, let's go ahead and create another route to a list of Employees from a stored procedure.

The following code will return a JSON response.