Simple Web Server And REST API Using NodeJS And Express

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 greater than 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

JavaScriptNodeJS
"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 interactiveIncludes: Server-side activity like backend APIs, executing commands, accessing and performing non-blocking operations, system services etc. and provides service on the 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 hardware
JavaScript is synchronous and blockingNodeJS is asynchronous and non-blocking

To learn more on JavaScript See:

1. Getting Started

Let's create a new template for our application with the-

npm init

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

{
  "name": "nodejs-demo-app",
  "version": "0.0.1",
  "description": "Simple server with NodeJS and Express",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Shrawan Adhikari",
  "license": "MIT"
}

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

console.log('hello world')

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

node index.js

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

{
  // ...
  "scripts": {
    "start": "node index.js",    
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  // ...
}

Now the script "start" can be run using the command npm start.

3. Web Server using built-in http module

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

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.
Note: remember to stop the previous instance if it's already running

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

Error: listen EADDRINUSE :::3001  # If error, stop other earlier instance of use different port

Now Lets serve the Json file. Steps to follows:

const http = require('http')

let myDetails = [
    { 
     "Author": "Hashnode", "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 successfully 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.

npm install express --save

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

{
  "dependencies": {
    "express": "^4.17.1"
  }
}

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

const express = require('express')
const app = express()

let blogDetails = [
  ...
]

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

// sending json response
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.