Build a Simple app with Node and Express and Read Data

Build a Simple app with Node and Express and Read Data

In my earlier post we have started learning about Node.js and built a Hello World application using Nodejs as a backend server. If you are entirely new to Nodejs I suggest you please visit that post to become updated.

In this post, I wish to introduce ExpressJs server which makes application creation from Nodejs a breeze!!

We shall also walkthrough step by step to build a simple app that uses Express to get response over the HTTP.

What is ExpressJs ?

As per the official ExpressJs website, Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It is built on top of Nodejs and offers tons of HTTP utility methods and middleware at your disposal, which help create a robust API quickly and easily.

Pre-requisites of following this post

You shall need to have

To check if Node is installed, open up Windows Command Prompt and type the following (Fig 1):

Fig 1

You will get a version (as shown it is 16.13.2 for me). If not, you can download the installer from Node official website

Get Started

For this tutorial, either use an existing folder or create a new folder. I used the same folder named “Node” that I used for the previous post (Hello World). Now browse to the folder (in command line use cd –> change directory command to bring the cursor to the desired directory) and issue npm init command (Fig 2).

Fig 2

npm init creates a package.json file inside the current directory and helps you manage dependencies (which will be used for making more complex features like Create, Read, Update, Delete (CRUD) operations

Use Express

First, install ExpressJs (or simply Express). You can do this by using npm install command. (When you install Node, npm (short form of Node Package Manager) is installed. This allows you to use these commands!!

Run npm install expess --save command on your Windows Command Prompt(simply command line) (Fig 3)

Fig 3

The –save flag saves express as a dependency in the package.json file. (Fig 4)

Fig 4

In the next step, create a file named server.js by clicking the new file + icon from within the root folder inside Visual Studio Code.

Now use express in server.js by requiring it (Fig 5)

Fig 5

Next you need to create a server that browsers can connect to. For this use the Express’s listen method (Fig 6)

Fig 6

Now run the command on command prompt as per Fig 7 (you can also use the Terminal window on Visual Studio code itself (if it disappears, click CTRL + ` and it will appear)

Fig 7

It will log on the console as follows and it suggests that it is listening on port 3000 (Fig 8)

Fig 8

Now browse to http://localhost:3000 and you’ll get the following screenshot (Fig 9)

Fig 9

Now this means that you can now communicate to your express server through the browser. This is where we begin the READ operation.

Under the hood, browsers (like Google Chrome) perform read operation when you visit a web page by sending a GET request to the server. You see Cannot GET/ because the GET request did not produce any response, meaning that the server sent nothing back to the browser.

In Express, we handle a GET request with the get method:

app.get(endpoint, callback)

endpoint is the requested endpoint. Its the part that comes after your domain name, say when I am visiting my previous post on https://kaushikroychowdhury.com/blog/learn-node-js-and-build-hello-world-example-from-scratch/ , the requested endpoint is anything that comes after the domain name https://kaushikroychowdhury.com, so the end point is /blog/learn-node-js-and-build-hello-world-example-from-scratch/ in the context. If you mouseover you see 5 overloads of the get method handlers (the second parameter shown as callback)

Fig 10

Callback tells the server what to do when the requested end point matches the endpoint in the URL. It takes two arguments: a request object and a response object

For this tutorial, let’s write “Welcome from Express” as the server response to the browser. We use the response object’s send method to write to the browser (Fig 10).

If you now run the application again on the command line (or terminal window) and again browse to http://localhost:3000 you will get the following view:

Fig 11

The message on the browser “Welocme from Express” in Fig 11 matches our expectation of the response returned from the server (Express). So let’s congratulate ourselves on this success!!

Serve an Index.html file on the browser

You shall have to edit the server.js file now to send the contents of the html page back to the browser. To carry this out, use the sendFile method of the res object.

So first create the Index.html file at the root of your project folder by clicking the VS Code New File icon on the root “Node” folder.

Next put the following markup in the Index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MY APP</title>
</head>
<body>
  <h1> May Node and Express be with you. </h1>
</body>
</html>

Now edit the server.js file as per the screenshot:

Fig 12

The {_dirname} evaluates the absolute path of the directory, so the line of code ${__dirname}/Index.html gives the path to the Index.html file.

Run the Application

If you now run the server and browse to localhost:3000/ you’ll see the following screen

Fig 13

This is how Express handles a GET request (READ operation) in a nutshell.

Follow Me Here

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.