Node.js + Express | A Beginners Guide

Write your first Node.js server app in 10 mins

Mayank Patel
5 min readMar 20, 2021

A Brief introduction to Node.js and Express.js

Node.js

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser.

Express.js

Express.js, or simply Express, is a back-end web application framework for Node.js, it is designed for building web apps and APIs. It has been called the de facto standard server framework for Node.js.

This article will guide you in writing a Node.js server application, with an appropriate project structure and will briefly introduce well-known packages which are generally used while working with Node Server Applications.

Let’s get Started

  • Create a new project folder mynodeserver
  • Make sure Node.js is installed on your workspace by node -v
  • run npm init in the terminal, this will create a package.json file.
package.json file holds the metadata about the project
  • create an app.js file
  • Create an Express Application in the app.js file.
const express = require('express')
const app = express()

before proceeding any further, we need to understand the meaning of the term middleware as it will keep popping up again and again in this article.

You can install any package used by npm install <package-name> --save

What is a Middleware?

Middlewares in Node.js are functions that a request goes through before reaching its designated endpoint, each middleware function has access to request and response objects and after performing the assigned task on the request it calls the next function passing the function further in the pipeline.

Developers can write any number of middlewares depending on the application, middleware functions are typically used for sanitizing inputs, logging purposes, authentication, parsing data in the request body, etc.

Body-Parser:

body-parser is a middleware module that helps in simplifying the request packet, body-parser extracts the entire body portion of an incoming request stream and exposes it on req.body.

There are mainly two parser used for parsing JSON bodies & urlencoded bodies

const express = require('express')
const app = express()
const bodyParser = require('body-parser')app.use(bodyParser.urlencoded({extended: true})
app.use(bodyParser.json())

Cors:

Don’t know what CORS is ? tap this link

cors is an another important middleware used for handling cross-origin-request to the server.

const express = require('express')
const app = express()
const bodyParser = require('body-parser')app.use(bodyParser.urlencoded({extended: true})
app.use(bodyParser.json())
const cors = require('cors')app.use(cors({
origin: true,
//this will allow request from all origin
credentials: true
//this will let credentials pass
}))

Cookie-Parser:

Parses Cookie header and populate req.cookies with an object keyed by the cookie names

const cookieParser = require('cookie-parser')app.use(cookieParser())

Morgan:

Logging request information plays an important role in the development process, helps to understand the request type, response status, response time, etc.

For logging all the request information hitting the server morgan middleware is used, read the morgan documentation for other configurations.

//logging information only if its not production environmentif (process.env.NODE_ENV != 'production'){  const logger = require('morgan')
app.use(logger('dev'))
}

ExpressValidator :

express-validator is a fabulous middleware used for input sensitization and validation, it has a pretty straight use-case and saves a lot of development time.

the middleware code
the middleware is added to /login endpoint and later checked if errors are empty or not.

Helmet:

helmet helps you secure your Express apps by setting various HTTP headers. It’s not a silver bullet, but it can help! , checkout the documentation for different use-cases.

const helmet = require("helmet");app.use(helmet());

Dotenv package:

dotenv is a zero-dependency module that loads environment variables from a .env file into process.env

const dotenv = require('dotenv')
dotenv.config()
// way to access environment variable
process.env.<environment variable name>

Before writing our endpoints we need to understand what is a Callback function

Callback Function

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Callback Hell

Callback hell is a phenomenon that afflicts a JavaScript developer when he tries to execute multiple asynchronous operations one after the other.

Ignore the async keyword for now, If you are not familiar with it.

Let’s add GET and POST endpoints to our express server.

Handling GET request on route /home and responding with JSON object :

app.get('/home', async (req, res) => {
res.status(200).json({
success: true,
msg: "home page"
})
})

Handling POST request on route /login and responding with JSON object containing request body.

app.post('/login', async (req, res)=>{
res.status(200).json({
success: true,
body: req.body
})
})

Understanding the response object (res), the response object represents the data that will be sent back to the client. The res object has multiple functions which can be used to set response status, cookies, response JSON data, headers, file attachments, or send plain text or render a template.

Listen on port: 3000

Express app listen function takes two parameters 1. PORT Number , 2. Callback function .

app.listen(3000, ()=> {
console.log('Server is listening on PORT 3000')
}

App.js file

Host Your Server

run command: node app.js from the project root.

Query the server on localhost:3000

There are multiple ways to test API, the most popular is by using cURL a command-line tool, or postman a desktop app with pretty simple UI and a ton of API testing features. Postman is the go-to application for testing an API.

It’s very simple to use Postman, select the request type from the drop-down, add request URL, add query parameters, Body data then press Send.

GET REQUEST | curl http://localhost/home
POST REQUEST

Hurray, You have hosted your first Node.js Server 🎉🎉

This is just an introductory Article with basics of writing a plain server application, the next article which will talk about project structure, routing, error handling, middlewares, promises or async-await function and much more 👌🙌

--

--