Getting Started with NodeJS

Setting Up Node.js

Setup a Node.JS application:

 

Step 1:

Make sure you have Node.Js and npm downloaded

 

Step 2:

Create a new folder, and open a terminal on the folder

Step 3:

In the terminal, run `npm init -y`

Now you should see a file named package.json in your folder

 

Step 4:

Add a index.js file in the root of your project

Setting Up Node.js

Creating your first Node.JS application with Express.Js

Go to index.js file:

Step 1:

Add the following code in the file:

// Import the express library
const expressApp = require("express")

// define the port
const PORT = 9000

// create the app (server) by calling the expressApp function
const app = expressApp()

// call the "listen" method on the app instance, 
// provide it with a port on which it should be open for connections
app.listen(PORT, () => console.log(`The server is running on port: ${PORT}`))

Setting Up Node.js

Creating your first Node.JS application with Express.Js

 

Go to index.js file:

Step 2:

Add your first API

 

// Import the express library
const expressApp = require("express")

// define the port
const PORT = 9000

// create the app (server) by calling the expressApp function
const app = expressApp()


// add the HTTP Method (get) on your app,
// define the path: "/users",
// add the logic
app.get("/user", (req, res, next) => {
  
  const { query, params, body } = req
  console.log({query, params, body})
  
  res.status(201).send("Users are there")
})

// call the "listen" method on the app instance, 
// provide it with a port on which it should be open for connections
app.listen(port, 
() => `The server is running on port: ${PORT}`)

Setting Up Node.js

Creating your first Node.JS application with Express.Js

 

Go to index.js file:

Step 3:

Test your app:

Run `npm start`

 

Check the package.json -> scripts -> start

{
  "name": "my-node-app",
  "version": "1.0.0",
  "main": "index.js",
    
  "scripts": {
    "start": "node index.js"
  }
}
npm start

Contents of Package.json

After you have done 'npm init -y', you get a package.json file in your folder.

This file has several data in an object:

name: the name of your NodeJS app

main: entrypoint of your NodeJs app, the code execution starts from this very file.

{
  "name": "my-node-app",
  "version": "1.0.0",
  "main": "index.js",
    
  "scripts": {
    "start": "node index.js"
  }
}
npm start

Contents of Package.json

version: it indicates the version of your NodeJs application. It's important when you're deploying your code.

This version is of 3 numbers (1.0.0):
 - Major update (1)

 - Minor update (0)

 - Patch update (0)

This is called semantic versioning.

{
  "name": "my-node-app",
  "version": "1.0.0",
  "main": "index.js",
    
  "scripts": {
    "start": "node index.js"
  }
}

Contents of Package.json

scripts:

this contains scripts or commands that you can run from terminal directly using package manager (npm).

You can run in terminal npm run <scripts-key>
Eg:

npm run start

npm run hello


 

{
  "name": "my-node-app",
  "version": "1.0.0",
  "main": "index.js",
    
  "scripts": {
    "start": "node index.js",
    "hello": "echo \"hello world\""
  }
}

Contents of Package.json

dependencies:

Dependencies are the libraries that we need to run our NodeJs application.

devDependencies:

Now the devDependencies are the libraries that are required for development, but are not required to run our application, they can be put in devDependencies.

This keeps our production build lightweight.

{
  "name": "tapish-test",
  "version": "2.7.7",
  "main": "src/server.js",
  "scripts": {
    "test": "echo \"nhi krna hai koii test\"",
    "dev": "nodemon src/server.js",
    "prod": "node src/server.js"
  },
  "dependencies": {
    "body-parser": "^1.20.2",
    "express": "^4.19.1",
    "pg": "^8.12.0"
  },
  "devDependencies": {
    "nodemon": "^3.1.3"
  }
}
npm i express
npm i express@4.19.2

npm i nodemon --save-dev
npm i nodemon@3.1.3 --save-dev

Creating APIs

const bodyParser = require("body-parser");
const expressApp = require("express");
const server = expressApp();
const PORT = 2334;
const userMap = {
  user1: {
    id: "Yash",
    password: "Asdasd",
  }
};
// parse application/json
server.use(bodyParser.json());

server.post("/user-post", (req, res, next) => {
  const { query, body, params } = req;
  console.log({ body, query, params });
  Object.assign(userMap, body);
  res.status(201).json(userMap);
});

server.get("/user-get", (req, res, next) => {
  console.log("user posted");
  res.status(203).json(userMap);
});

server.get("/login", (req, res, next) => {
  const { userid, password } = req.body;
  const user = Object.keys(userMap).find((user) => {
    return userMap[user].id === userid && userMap[user].password === password;
  });
  if (user) {
    res.status(203).json(user);
  } else {
    res.status(401).json("User not found");
  }
});

server.listen(PORT, () => console.log(`Server is listening on PORT: ${PORT}`));
  • Creating POST APIs,
  • Create GET APIs
  • Sending Response as JSON
  • Passing data through API in queryParams
  • Passing data through API in body
  • Using bodyParser for accessing API body data,
  • Sending different HTTP status codes in response

Request and Response

const bodyParser = require("body-parser");
const expressApp = require("express");
const server = expressApp();
const PORT = 2334;
const userMap = {
  user1: {
    id: "Yash",
    password: "Asdasd",
  }
};

// parse application/json
server.use(bodyParser.json());

server.post("/user-post", (req, res, next) => {
  const { query, body, params } = req;
  console.log({ body, query, params });
  Object.assign(userMap, body);
  res.status(201).json(userMap);
});

server.get("/user-get", (req, res, next) => {
  console.log("user posted");
  res.status(203).json(userMap);
});

server.get("/login", (req, res, next) => {
  const { userid, password } = req.body;
  const user = Object.keys(userMap).find((user) => {
    return userMap[user].id === userid && userMap[user].password === password;
  });

  if (user) {
    res.status(203).json(user);
  } else {
    res.status(401).json("User not found");
  }
});

server.listen(PORT, () => console.log(`Server is listening on PORT: ${PORT}`));

Request: When API call is made from the client (React) to the server (NodeJs)

Response: The server (Nodejs, receives the request, and it replies/sends a response back.

Request and Response have some important parts:

  1. Headers,
  2. Body / Query / Params,
  3. HTTP Status Codes,
  4. HTTP Methods

Request and Response

Request Headers:

  1. Authorization
  2. Content-Type
  3. Accept
  4. User-Agent
  5. Cache-Control
  6. Referer

Response Headers:

  1. Content-Type
  2. Content-Length
  3. Cache-Control
  4. Set-Cookie
  5. Location
  6. Access-Control-Allow-Origin

Request Headers

Authorization

  • Meaning: This header is used to provide credentials for authenticating a user with a server.
  • Values:
    • Basic <base64-encoded-credentials>
    • Bearer <token>
    • Digest <parameters>
Usage Example:

// Basic Authentication:
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
// This encodes the username and password in base64 
// and sends it to the server for basic authentication.

// Bearer Token (JWT):
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
// This sends a JWT token to authenticate API requests.

Request Headers

Content-Type

  • Meaning: Indicates the media type of the resource being sent.
  • Values:
    • text/html
    • application/json
    • multipart/form-data
Usage Example:


// Sending JSON Data:
Content-Type: application/json
// This header is used when sending 
// JSON data to the server.


// Uploading a File:
Content-Type: multipart/form-data
// This is used for file uploads in forms.

Request Headers

Accept

  • Meaning: Specifies the media types that the client is able to understand.
  • Values:
    • text/html
    • application/json
    • image/png
Usage Example:
// Accepting JSON Responses:

Accept: application/json
// This informs the server that the client expects a JSON response.

Request Headers

User-Agent

  • Meaning: Contains information about the user agent (browser) making the request.
  • Values: Varies widely depending on the browser and operating system.
    • Example: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
Usage Example:

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
// This header identifies the client's browser and operating system.

Request Headers

Cache-Control

  • Meaning: Directs caching mechanisms on how to cache the request and response.
  • Values:
    • no-cache
    • no-store
    • max-age=<seconds>
Usage Example:

// Fetching Fresh Data:
Cache-Control: no-cache
// This ensures that the request fetches 
// fresh data rather than using a cached response.


// Caching for an Hour:
Cache-Control: max-age=3600
// This tells the cache to store the 
// response for one hour.

Request Headers

Referer

  • Meaning: Contains the URL of the resource from which the request originated.
  • Values: URL of the referring page.
    • Example: Referer: https://example.com/previous-page
Usage Example:

Referer: "https://example.com/home"
// This informs the server about the origin 
// of the request for tracking purposes.

Response Headers

Content-Type

  • Meaning: Indicates the media type of the resource being sent back by the server.
  • Values:
    • text/html
    • application/json
    • image/jpeg
Usage Example:

// Returning JSON Data:

Content-Type: application/json
// This indicates that the 
// response body contains JSON data.

Response Headers

Content-Length

  • Meaning: Indicates the size of the response body in bytes.
  • Values: Integer representing the number of bytes.
    • Example: Content-Length: 348
Usage Example:

Content-Length: 1024
// This informs the client about 
// the size of the data being transferred.

Response Headers

Cache-Control

  • Meaning: Directs caching mechanisms on how to cache the response.
  • Values:
    • no-cache
    • no-store
    • max-age=<seconds>
Usage Example:

// Caching Static Assets:

Cache-Control: public, max-age=86400
// This tells the cache to store the response for a day, 
// which is useful for static assets like images.

Response Headers

Set-Cookie

  • Meaning: Sends cookies from the server to the client to store.
  • Values:
    • Set-Cookie: <name>=<value>; Expires=<date>; Path=<path>; Domain=<domain>; Secure; HttpOnly
Usage Example:

Set-Cookie: sessionId=abc123; Path=/; HttpOnly
// This sets a session cookie to maintain 
// user sessions across multiple requests.

Response Headers

Location

  • Meaning: Used in redirection or when a new resource has been created.
  • Values: URL to which the client should be redirected.
    • Example: Location: https://example.com/new-page
Usage Example:


Location: "https://example.com/login"
// This redirects the client to the login 
// page after successful registration.

Response Headers

Access-Control-Allow-Origin

  • Meaning: Specifies which origins are allowed to access the resource via CORS.
  • Values:
    • * (any origin)
    • Specific origin: Access-Control-Allow-Origin: https://example.com
Usage Example:


// Allowing Any Origin:
Access-Control-Allow-Origin: *
// This allows any origin to access the resource.


// Specific Origin:
Access-Control-Allow-Origin: https://example.com
// This allows only example.com to access the resource.

Using Express Routes

// server.js

const express = require('express');
const app = express();
const port = 3000;
// Import users routes
const usersRouter = require('./routes/users');
// Use users routes
app.use('/users', usersRouter);

app.listen(port, () => {
    console.log(`Server is running on 
				http://localhost:${port}`);
});
// routes/userRoutes.js
const express = require('express');
const router = express.Router();

// Define routes for users
router.get('/', (req, res) => {
    res.send('Hello, World!');
});

router.get('/:id', (req, res) => {
    res.send('About Page');
});

router.post('/submit', (req, res) => {
    res.send('Form submitted');
});

module.exports = router;
// server.js

const express = require('express');
const app = express();
const port = 3000;

// Home route
app.get('/users/', (req, res) => {
    res.send('Hello, World!');
});

// About route
app.get('/users/:id', (req, res) => {
    res.send('About Page');
});

// Example of a POST route
app.post('/users/submit', (req, res) => {
    res.send('Form submitted');
});

app.listen(port, () => {
    console.log(`Server is running 
				on http://localhost:${port}`);
});

Adding API controllers

// server.js

const express = require('express');
const app = express();
const port = 3000;
// Import users routes
const usersRouter = require('./routes/users');
// Use users routes
app.use('/users', usersRouter);

app.listen(port, () => {
    console.log(`Server is running on 
				http://localhost:${port}`);
});
// routes/userRoutes.js
const express = require('express');
const router = express.Router();
const getUserById = require('/controllers/getUserById')

// Define routes for users
router.get('/', getUserById);

router.get('/:id', (req, res) => {
    res.send('About Page');
});

router.post('/submit', (req, res) => {
    res.send('Form submitted');
});

module.exports = router;
// controllers/getUserById.js
const express = require('express');
const router = express.Router();

// Define routes for users
const getUserById = async (req, res, next) => {
    res.status(200).json('Hello, World!');
});

module.exports = {
  getUserById
};

Middlewares in Express

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

// Middleware function
const loggerMiddleware = (req, res, next) => {
    console.log(`${req.method} ${req.url}`);
  // Pass control to the next middleware or route handler
    next(); 
};

// Apply middleware to all routes
app.use(loggerMiddleware);

// Route handlers
app.get('/', (req, res) => {
    res.send('Hello, World!');
});

app.post('/submit', (req, res) => {
    res.send('Form submitted successfully!');
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

Middlewares In Express:

  • Middleware in Express.js provides a way to perform tasks during the request-response cycle.
  • Middleware functions have access to the request object (req), response object (res), and the next function in the application's request-response cycle.
  • Middlewares are simple JavaScript functions.
  • They can be added between API routes or with app.use() syntax
  • Eg:
    bodyParser.json(),
    cors()

Middlewares in Express

const express = require('express');
const app = express();
const router = express.Router();

// Middleware function
const authMiddleware = (req, res, next) => {
    if (req.query.token === 'secret_token') {
        next(); // Proceed to the next middleware or route handler
    } else {
        res.status(401).send('Unauthorized');
    }
};

// Apply middleware to the router
router.use(authMiddleware);

// Route handlers
router.get('/', (req, res) => {
    res.send('Welcome to the protected area!');
});

router.post('/create', (req, res) => {
    res.send('Resource created successfully!');
});

// Mount the router on a path
app.use('/api', router);

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

Middlewares In Express:

  • The authMiddleware function checks if a query parameter token with a value of 'secret_token' is present in the request.
  • The middleware is applied to the router using router.use(authMiddleware).
  • All routes defined within the router are protected by the middleware.
  • The router is mounted on the /api path using
    app.use('/api', router).
  • The execution moves from line 27 to line 15

Getting Started with NodeJS

By Yash Priyam

Getting Started with NodeJS

  • 82