Anandi Sheladiya
Contact
  • About Anandi
  • SKILLS & EXPERIENCE
    • Frontend
      • ReactJS
      • Next.js – The React Framework for Production
      • ChartJS / D3.JS / Fabric JS
      • Three.JS: The JavaScript Library for 3D Graphics
      • HTML/CSS/JS/Tailwind CSS/Bootstrap
      • Material UI – The Ultimate React UI Framework
      • ShadCN/UI – The Modern UI Library for React
    • Backend
      • NodeJS & ExpressJS
      • Web3.JS
      • Python & Django
      • GoLang
      • TypeScript
    • Database
      • PostgreSQL
      • MongoDB - NOSQL Database
      • MySQL
    • API
      • REST API
      • GraphQL API
      • RPC (Remote Procedure Call)
      • WebSocket
    • Solidity
    • Layer 1 Blockchain
      • Ethereum
      • Solana
      • Bitcoin
      • Hyperledger
      • Binance
      • Avalanche
      • Cardano
      • Polkadot
      • Near Protocol
      • Algorand
      • TON (Telegram Open Network)
    • Optimistic Rollups (L2 on Ethereum)
      • Arbitrum
      • Base
      • Mantle
    • ZK-Rollups (L2 on Ethereum)
      • zkSync Era
      • Polygon zkEVM
    • Wallet Integration
      • Reown Appkit
      • Rainbow Walletkit
      • Web3 Modal
      • WalletConnect
      • Wagmi
      • Metamask & Safewallet SDKs
    • Web3 SDKs & API Providers
      • Alchemy
      • Moralis
      • QuickNode
      • BitQuery API & Stream
      • ThirdWeb
      • Infura
      • Li.Fi
      • 1Inch API
      • Uniswap API
      • OpenZeppelin
    • Web3 Middleware/ UX Infrastructure Platform
      • Biconomy
      • Pimlico
      • Alchemy AA
      • Safe (formerly Gnosis Safe)
      • ZeroDev
    • On Chain Trading Platform & Telegram Bot
      • Bullx
      • Wave Bot
      • GMGN
      • Shuriken
      • Magnum Trade
      • Trojan
  • PROTOCOLS
    • ERCs & EIPs
      • ERC-20: The Standard for Fungible Tokens
      • ERC-721: The Standard for Non-Fungible Tokens (NFTs)
      • ERC 4337
      • ERC 6551: Token Bound Accounts (TBA)
      • ERC 7702
      • EIP 4844 (Proto-Danksharding)
      • Ethereum Pectra
  • ARTICLES
    • Medium
Powered by GitBook
On this page
  • Introduction
  • Why Use Node.js?
  • Why Use Express.js?
  • Getting Started with Node.js & Express.js
  • 1️⃣ Install Node.js
  • 2️⃣ Initialize a New Project
  • Creating a Simple Express Server
  • Express.js Routing
  • Using Middleware in Express.js
  • Serving Static Files (HTML, CSS, Images, JS)
  • Handling Forms & JSON Data
  • Connecting Express.js with a Database
  • MongoDB (Using Mongoose)
  • Building a REST API with Express.js
  • Real-time Apps with Socket.io
  • Conclusion

Was this helpful?

  1. SKILLS & EXPERIENCE
  2. Backend

NodeJS & ExpressJS

Introduction

Node.js is a powerful, event-driven, non-blocking JavaScript runtime that allows developers to build scalable and high-performance backend applications. It is built on Google Chrome's V8 JavaScript engine, making it fast and efficient for server-side development.

Express.js is a lightweight and flexible web framework for Node.js, designed to simplify the process of building web applications and APIs. It provides essential features like routing, middleware, and HTTP handling, making backend development smoother.

Why Use Node.js?

  • Asynchronous & Non-blocking – Handles multiple requests efficiently.

  • High Performance – Uses V8 Engine, which compiles JavaScript to machine code.

  • Single Programming Language – JavaScript can be used for both frontend & backend.

  • Huge Ecosystem – Over 1.5 million packages available via npm.

  • Microservices & Real-time Apps – Ideal for APIs, chat apps, and live streaming.

  • Scalability – Perfect for handling thousands of concurrent users.

Why Use Express.js?

  • Minimal & Fast – No unnecessary bloat; just the essentials.

  • Easy Routing System – Handles URLs efficiently.

  • Middleware Support – Customize requests and responses.

  • Template Engines – Supports EJS, Pug, and Handlebars for dynamic HTML.

  • API Development – Ideal for creating RESTful & GraphQL APIs.

Getting Started with Node.js & Express.js

1️⃣ Install Node.js

node -v   # Check Node.js version
npm -v    # Check npm version

2️⃣ Initialize a New Project

Create a new project and set up package.json:

mkdir myapp && cd myapp
npm init -y

3️⃣ Install Express.js

npm install express

Creating a Simple Express Server

Create a server.js file and add the following:

const express = require("express");
const app = express();
const PORT = 3000;

app.get("/", (req, res) => {
  res.send("Hello, World! 🌍");
});

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

Run the server:

node server.js

Now, open http://localhost:3000/ in your browser.

Express.js Routing

Defining Different Routes

app.get("/", (req, res) => {
  res.send("Home Page");
});

app.get("/about", (req, res) => {
  res.send("About Page");
});

app.post("/submit", (req, res) => {
  res.send("Data Submitted Successfully");
});

Handling URL Parameters

app.get("/user/:name", (req, res) => {
  res.send(`Hello, ${req.params.name}!`);
});

Visit: http://localhost:3000/user/John Output: "Hello, John!"

Using Middleware in Express.js

Middleware functions allow you to modify requests/responses before they reach the final handler.

Example of Middleware

app.use((req, res, next) => {
  console.log(`Incoming Request: ${req.method} ${req.url}`);
  next(); // Call the next middleware or route handler
});

Built-in Middleware

app.use(express.json());       // Parse JSON requests
app.use(express.urlencoded({ extended: true }));  // Parse form data

Third-party Middleware (CORS, Morgan)

npm install cors morgan
const cors = require("cors");
const morgan = require("morgan");

app.use(cors());   // Enables cross-origin requests
app.use(morgan("dev")); // Logs requests in console

Serving Static Files (HTML, CSS, Images, JS)

Express can serve static files from a directory like public/.

app.use(express.static("public"));

Place HTML, CSS, JS, images inside the public/ folder, and access them directly in the browser.

Handling Forms & JSON Data

Install Body Parser (Optional, built-in in Express 4.16+)

npm install body-parser

Parse Form Data & JSON Requests

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

Handling Form Submissions

app.post("/login", (req, res) => {
  const { username, password } = req.body;
  res.send(`Logged in as ${username}`);
});

Connecting Express.js with a Database

MongoDB (Using Mongoose)

Install Mongoose

npm install mongoose

Connect to MongoDB

const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/mydb", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const UserSchema = new mongoose.Schema({ name: String, age: Number });
const User = mongoose.model("User", UserSchema);

// Create a User
app.post("/users", async (req, res) => {
  const user = new User(req.body);
  await user.save();
  res.send("User saved!");
});

Building a REST API with Express.js

Create a Simple API

const products = [
  { id: 1, name: "Laptop", price: 1000 },
  { id: 2, name: "Phone", price: 500 },
];

// Get all products
app.get("/api/products", (req, res) => {
  res.json(products);
});

// Get a single product by ID
app.get("/api/products/:id", (req, res) => {
  const product = products.find((p) => p.id == req.params.id);
  product ? res.json(product) : res.status(404).send("Not found");
});

// Create a new product
app.post("/api/products", (req, res) => {
  const newProduct = req.body;
  products.push(newProduct);
  res.status(201).json(newProduct);
});

Real-time Apps with Socket.io

Install Socket.io

npm install socket.io

Simple WebSocket Chat App

const http = require("http").createServer(app);
const io = require("socket.io")(http);

io.on("connection", (socket) => {
  console.log("User connected");
  socket.on("message", (msg) => io.emit("message", msg));
});

http.listen(3000, () => console.log("Chat server running on port 3000"));

Conclusion

Node.js & Express.js are powerful tools for building scalable, fast, and efficient backend applications. Whether you're creating REST APIs, real-time apps, or full-stack projects, they provide everything you need.

PreviousBackendNextWeb3.JS

Last updated 3 months ago

Was this helpful?

Download and install Node.js from . Check the installation:

https://nodejs.org