Querying SQL Server with Node.js

Adding a Node Web Server

gravity well
Nov 10 · 9 min read
Photo by fabio on Unsplash

What We Are Doing

We are taking the work done in my prior article up a notch. In that article we queried a SQL Server Database with node.js

Now we want to add a node Web Server so that we can Post data to the node web server, use it in the Database Query and return results back to a web page.

This will be a “first principles” exercise (you’ll understand later.)

As I stated before,

and also,

What We Want To Accomplish

  • Create a node Web Server.
  • Post Data from a Web Page to use in our SQL Server Database Query.
  • Send Results back to a Web Page.

What We Will Use

Along with existing the node packages and modules we will require only new ones.

  • express — a popular web framework
  • body parser — to assist in getting form data from a web page.

Other than that, we will keep things as plain (vanilla) JavaScript (first principles) as possible.

Why keep things as vanilla JavaScript? Because seeing how things can be done from “first principles” not only gives us appreciation for additional modules, frameworks and libraries out there (React, Vue, etc.) but may also make us realize, “hey, I don’t really need all that.”

We may eventually want the power of React or Vue but why carry that weight if we do not need to.


It is not necessary to read the prior article first as I’ll be going over the core of what we need, but it may be of benefit.

If nothing else, you may want to look at my Database Setup. Yours can be completely different but I have links to download some useful tools for free if you do not have access to a SQL Server.


Let’s Get Started

I will assume you have node.js installed but if not, it can be downloaded here.

We will start off by setting up our node.js Web Server and testing it. Then add similar code as before to Connect to and Query our SQL Server Database.

We will use the Minimalist Web Server framework for node.js, Express. It installs as an npm package.

As with many things, there is always more to learn so when I have you type a command, certainly read more about the command and it’s options.

Getting Set Up

  1. For the project, create a directory/folder.
  2. Open Visual Studio Code (VSCode) and open the folder.
  3. Open a new Terminal window and type,
    npm init
    Accepts the defaults to create your package.json.

4. Create a file in VSCode and save it as index.js. If you look in your package.json file, you will see where you can change the default “main” file.

Basic starting point

5. In the Terminal window type,
start npm
This starts the node.js server.

The Web Server

In the Terminal window type,
npm install express

This installs the Web Framework.

We are ready to rock and roll!

The core of the Web Server is to require the express package and assign it to a holder (variable or const.) All references to the Web Server will be through this holder.

We have to start the web server and have it listen on an HTTP port, I’ll choose 5000. 8080 is common, just something available.

We will want the Web Server to at least respond to an HTTP get method. This will allow use to “kick the tires” and make sure it works. There is more in HTTP methods here on the MDN. We will use GET and POST.

  • GET is used to retrieve from a resource.
  • POST is used to submit to a resource.

Enter the following code and we will discuss it.

Web Server Example

The core set up.
  • We require the express package, storing the reference in express by convention, but name it as desired.
  • Initialize an instance of express, storing the reference in app by convention, but name it as desired.
  • In line 11, we store a reference to where our web server will be listening. Port 5000.
  • In line 5, we use the HTTP GET with out instance of the web server using app.get. This, by default will look to get data from the root directory (‘/’). The callback function is quite important as it contains the Request (req) and Response (res) objects. The names req and res are by convention.

Request and Response

  • Request will be coming from our browser’s url. More information can be found here.
  • Response is the response to a request. More can be found here.

In a nutshell, our browser will make a Request and we will send back a Response.

Side Note: I actually prefer the ES6 syntax in lines 5 and 11 above. By this I mean, I prefer Arrow functions. For example, in line 5, I would typically not write app.get(‘/’, function(res,resp){… but write app.get(‘/’),(res,resp)=>{… and in line 11, instead of app.listen(5000,function(){…I would write app.listen(5000,()=>{

Kick the Tires

  1. In VSCode, hit F5 (short for Start Debugging in the Debug menu.) Your console should look as follows.
Look for the console message. The top has controls for stopping/refreshing, etc.

2. Go to your Browser and type LocalHost:5000 and hit Enter. You should see the following.

Yay!

Your browser made a GET Request and we sent back a Response using res.send.

Node SQL Server Connection

(Optional if done before.) In the Terminal window, type
npm install mssql
This installs the SQL Server Drivers.

Database Example

This is the exact same starting code as my prior article so I will not be going over it in detail. However, it’s position in the app object will be important.

A couple of things to note that will be different from before, after our initial test,

  • the PerformanceRating of our Employees will be sent from a Web Page (POSTed.)
  • the result of the Query will be output to a Web Page using Response.

Database Connection/Query Example

Enter the code below.

Something important to note is we have a Web Server and a Database connection and Query. But they do not interact. Yet!

Disconnected Web Server and Database Connection

Run it with by stopping and starting the web server or refreshing

Refesh/Stop and other options

and you will see the web server is running and there is console output of the data from the query. But we are not getting anything from the web server nor sending anything out to a web page.

Our web server note and Database Query Output

The HTML

We need a page to serve up when the user goes to our site. This page will allow them to send a parameter (PerformanceRating) that can be used in the Database Query.

Note: I am not going to be concerned about styling our web page. It will be simple and to the point.

We are also saving everything in the root. A best practice? No way! But we are going for functionality. Clean up can happen later.

  1. Create the following web pages and name them index.html and Employees.html.
  • index.html will be our main source page.
  • Employees.html will be where our result ends up.
Simple startup page, index.html

Note the <form action=”/Employees…
This is where our output will go.

Add the following to Employees.html

2. This next step is going to require a couple of things. One of which is how I am choosing to serve up index.html. Other sources you read may get in to routing. Routing is a very important area, but outside our scope. Our way is just one of many ways. The new additions to our code will be,

  • path — this will help us used res.sendFile to server up the file we want when a visitor comes to our site.
  • bodyParser — makes form data available once a POST is done
  • sendFile — allows you to serve up the desired default page.

Make the following changes to your code,

path, bodyParser and sendFile

Run it with by stopping and starting the web server or refreshing. In your browser, after refreshing the browser,you should see,

index.html served up by default

Using the HTML Form Data In Our Query

For this, we need to add an app.post. This will engage whatever we desire when the index.html for is POSTed from the web page.

This is an important step. Our Database Connection and Query need to be inside the app.post callback function.

Note how our Database components go in the app.get
  • Line 13 starts the app.post. In the body of the callback are our Database components.
  • Line 52 closes the app.post.

Could we structure all this differently, yes. I’m doing it this way to give us a foundation that will work. Then we/you can explore other options

Using the Form Data

Using the form data will be easy.

Lines 35, 37, 50 and 55
  • Line 35, get the form data from the Select element. bodyParser is what is helping us here. req.body.elementname.
  • Line 37, the Query, uses the value from the form.
  • Line 50 is sending the raw queried data to Employees.html.

Run it by stopping and starting the web server or refreshing.

  1. Go to your web page and refresh.

2. Choose “Average” from the rating drop down and click “Get Results”

3. You should get output in Employees.html. Not attractive, but it’s a start.

Json output from res.send

Last Steps — Clean Up The Output (a bit.)

This is the easiest and hardest part. Hardest because there are so many options. We are going to go with the basics of the basics so we get a glimpse of what is happening deep down inside.

This is an area you are going to want to explore in much more in detail. Not just additional methods of res, but the idea of a “view engine”.

And I will be exploring some of these in future articles. In particular, one of my favorites, express-handlebars.

For now, we are going to construct our output. Yes. Construct it ourselves. Build a table of our data in code and send it! Just loop through our data.recordset and build.

See the following

Building our output

You will want to add lines 50–57.

The output will be as follows when Querying for “Average”

Built by us with code.

What To Do Next (yes you)

Play with it, add more, change the structure. Work starting from basics, and work up.

Conclusion

We are working with first principles to help us understand what goes on behind some of the layers that are added by JavaScript templates, frameworks and libraries these days.

We have built on our own, a full-stack system. Yes, believe it or not we have.

What needs the most work, the output. But this whole exercise opens up a world of exploration and opportunities. So we want to expand the concepts of,

  • More CRUD operations
  • Routing
  • View engines/templates

Thank you for taking this journey and we will explore more.

JavaScript in Plain English

Learn the web's most important programming language.

gravity well

Written by

Long time Software Developer, Trainer, Consultant. Keeping up to date. I’ve noticed in over 28 years of programming, one’s current skills have a shelf life.

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade