Node API With SQL Server

Introduction

Node js is an open source server-side runtime environment. It provides asynchronous programming which means no blocking of a task. Due to this, it is faster than other frameworks. Node js is cross-platform that runs on Windows, Linux, and Mac. So, we can create a server-side application using JavaScript which is very fast and lightweight. Let us start building an application with node.
 
Description

Before we begin with node, we have to make sure that we have installed the node.js on our system. So, follow the following link and download node setup according to your operating system. Click here to download node setup After installing it successfully, go to your Start window and search for (Node.js command prompt). Open it and let's start with this.
 
Step 1

Write the following commands in your Node.js command prompt.
  1. F:\Projects>mkdir NodeApiWithSql  
  2. F:\Projects>cd NodeApiWithSql  
  3. F:\Projects\NodeApiWithSql>npm init  
It will create a file in your NodeApiWithSql folder with the name package.json with some basic information regarding your application.



You can see in the above image that it has created a file with the name, package.json, with the information related to your application. Now, let's see what we have in the package.json file.



You can see that in main, "index.js" is written in the package.json file. So, let's create a JS file with the name index in your folder. And let's install some required packages we need in our application with Node js command prompt.
Write the following commands in command prompt.



We have installed three packages here.
  • npm install express - is used for minimalist web framework for node.
  • npm install body-parser - body-parser incoming request bodies in a middleware.
  • npm install mssql - is used for using SQL Server database.
You can see more description regarding above packages at www.npmjs.com/package/
 
Now let's write following code in our index.js file -:
  1. var _expressPackage = require("express");  
  2. var _bodyParserPackage = require("body-parser");  
  3. var _sqlPackage = require("mssql");  
  4. //Initilize app with express web framework  
  5. var app = _expressPackage();  
  6. //To parse result in json format  
  7. app.use(_bodyParserPackage.json());  
  8.   
  9. //Here we will enable CORS, so that we can access api on cross domain.  
  10. app.use(function (req, res, next) {  
  11.     res.header("Access-Control-Allow-Origin""*");  
  12.     res.header("Access-Control-Allow-Methods""GET,HEAD,OPTIONS,POST,PUT");  
  13.     res.header("Access-Control-Allow-Headers""Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");  
  14.     next();  
  15. });  
  16.   
  17. //Lets set up our local server now.  
  18. var server = app.listen(process.env.PORT || 4000, function () {  
  19.     var port = server.address().port;  
  20.     console.log("App now running on port", port);  
  21. });  
  22.   
  23. //Set up your sql connection string, i am using here my own, you have to replace it with your own.  
  24. var dbConfig = {  
  25.     user: "sa",  
  26.     password: "@password1",  
  27.     server: "LAPTOP-7G1PNTT6",  
  28.     database: "SchoolManagment"  
  29. };  
  30.   
  31. //Function to connect to database and execute query  
  32. var QueryToExecuteInDatabase = function (response, strQuery) {  
  33.     //close sql connection before creating an connection otherwise you will get an error if connection already exists.  
  34.     _sqlPackage.close();  
  35.     //Now connect your sql connection  
  36.     _sqlPackage.connect(dbConfig, function (error) {  
  37.         if (error) {  
  38.             console.log("Error while connecting to database :- " + error);  
  39.             response.send(error);  
  40.         }  
  41.         else {  
  42.             //let's create a request for sql object  
  43.             var request = new _sqlPackage.Request();  
  44.             //Query to run in our database  
  45.             request.query(strQuery, function (error, responseResult) {  
  46.                 if (error) {  
  47.                     console.log("Error while connecting to database:- " + error);  
  48.                     response.send(error);  
  49.                 }  
  50.                 else {  
  51.                     response.send(responseResult);  
  52.                 }  
  53.             });  
  54.         }  
  55.     });             
  56.  }  
  57.   
  58. //GET API  
  59. app.get("/StudentList"function(_req ,_res){  
  60.     var Sqlquery = "select * from tbl_studentdetails";  
  61.     QueryToExecuteInDatabase(_res, Sqlquery);  
  62. });  
 Now your get api is ready, now let's run the code and if everything is fine code will be run successfully. So go to your node command prompt and write following command -:
 
 So you can see that our code is running successfully on 4000 port, now go to browser and write "localhost:4000/StudentList" , you will see the result like below image.
 
So we created an api in node with sql server and run successfully on our local server. Now lets call a stored procedure from node. I have created following stored procedure in sql server.
  1. ALTER PROCEDURE [dbo].[sp_CheckLogin]   
  2. @Username varchar(50),  
  3. @Password varchar(50)  
  4. AS  
  5. BEGIN  
  6.     -- SET NOCOUNT ON added to prevent extra result sets from  
  7.     -- interfering with SELECT statements.  
  8.     SET NOCOUNT ON;  
  9.     SELECT Userid,Username,IsActive from Membership_User where Username=@Username and Password=@Password and IsActive=1  
  10. END  
Now let's call this stored procedure with node, write following code -:
  1. var request = new _sqlPackage.Request();  
  2.    //calling a stored procedure  
  3.                 request.input('Username', _sqlPackage.VarChar(50), 'admin');  
  4.                 request.input('Password', _sqlPackage.VarChar(50), 'admin@123');  
  5.                 request.execute('sp_CheckLogin'function (err, recordsets, returnValue) {  
  6.                     response.send(recordsets);  
  7.                 });  
I have just write above code to call stored procedure from node, you just have to implement the way we implemented above get api. And when you will run this code you will see result like this.
 
So that's it for now, we will do something else in further blog, till enjoy coding.
 
 
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now