Contents

Simple Web Server And REST API Using NodeJS And Express

/nodejs-simple-web-server-and-rest-api/thumbnail.jpg
Simple Web Server using NodeJS

NodeJS, is a JavaScript run-time based on Google’s Chrome V8 JavaScript engine.

Introduction

To get started - Please make sure that your version of Node is at least v10.18.0 or later.
You can check your node version using: node -v . Or if you haven’t installed it yet, install the NodeJS from here- https://nodejs.org/en/

NodeJS vs JavaScript

JavaScript NodeJS
“Referring only JavaScript” means code running on the client-side (i.e on the browser). “Whereas NodeJS” is a unique implementation of JavaScript running on the server side.
Includes: Client side activity like clicks, animation, popup, etc. and makes web page interactive Includes: Server side activity like backend APIs, executing commands, accessing and performing non-blocking operations, system services etc. and provides service on level of operating system
JavaScript: simply runs on browser engines, like Spider monkey (FireFox), JavaScript Core (Safari), V8 (Google Chrome) etc. NodeJS: simply the V8 engine bundled with libraries to do I/O, networking, backend services and lot more on system server and harware
JavaScript is synchronous and blocking NodeJS is asynchronous and non-blocking

To learn more on JavaScript See:

1. Getting Started

Lets create a new template for our application with the-

1
npm init

Initialize project name and enter the promoted details.
This will generated the package.json file at the root of the project.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
  "name": "Node Learners",
  "version": "0.0.1",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Matti Luukkainen",
  "license": "MIT"
}

We have initializer for our app. main: “index.js” , is the entry point of the application Edit the index.js with the following code:

1
console.log('hello world')

We can run the program directly with Node from the command line:

1
node index.js

or we can edit and the script, in our package.json to run as npm script.

1
2
3
4
5
6
7
8
{
  // ...
  "scripts": {
    "start": "node index.js",    
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  // ...
}

Now the script “start” can be run using command npm start.

3. Web Server using built in http module

Now, Lets Write code for starting web server. In your index.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const http = require('http')

const app = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' })
  res.end('Hello World')
})

const port = 3001
app.listen(port)
console.log(`Server running on port ${port}`)

Start the app npm start or node index.js to run.

We can now open our application in the browser http://localhost:3001. Note: You may get the error - “Error Address in use 3001. This may happen if you didnt stop the previous instance you started or some app is using the port.

1
Error: listen EADDRINUSE :::3001 

Now Lets serve the Json file. Steps to follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const http = require('http')

let myDetails = [
	{ 
	 "Author": "GeekLearners", "Post": "Node Js with Express" 
	}
] 
const app = http.createServer((request, response) => {
  response.writeHead(200, { 'Content-Type': 'application/json' })
  response.end(JSON.stringify(myDetails))
})

const port = 3001
app.listen(port)
console.log(`Server running on port ${port}`)

We have sucessfuly created the app. However, serving the application with Node’s built-in http is cumbersome, especially once the application grows in size. Now comes the Express, the most popular library for running our web server.

4. Web server using Express library

Let’s install express in our application and quickly get started with it.

1
npm install express --save

–save will also add it to our package.json file

1
2
3
4
5
{
  "dependencies": {
    "express": "^4.17.1"
  }
}

Let’s get back to our application and make the following changes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const express = require('express')
const app = express()

let blogDetails = [
  ...
]

app.get('/', (req, res) => {
  res.send('<h1>Hello World!</h1>')
})

app.get('/api/details', (req, res) => {
  res.json(blogDetails)
})

const PORT = 3001
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`)
})

Start the app. npm start.