Node.js Express.js

πŸš€ Express.js – Complete Introduction

Express.js is the most popular web framework for Node.js.
It is fast, flexible, lightweight, and perfect for building APIs and web applications.


βœ… What is Express.js?

Express.js is a minimal and unopinionated web framework built on top of Node’s HTTP module.

βœ” Helps you create:

  • REST APIs

  • Web servers

  • Backend logic for web/mobile apps

  • Real-time and single-page applications

βœ” Why it is popular?

  • Simple and fast

  • Huge community

  • Flexible middleware system

  • Works with any database

  • Easy routing


πŸ“¦ Install Express.js

Create a project:

mkdir myapp
cd myapp
npm init -y

Install Express:

npm install express

🧩 Simple Express Server (Hello World)


 

Run:

node app.js

Visit in browser:

http://localhost:3000

πŸ›£οΈ Routing in Express.js

Routing defines how your server responds to requests.

Basic Routes


πŸ“₯ Handling Request Body (JSON)

Enable JSON parser middleware:

Receive data:


🧱 Express Middleware

Middleware = Functions executed between request & response.

Built-in Middleware:

  • express.json() – Parse JSON

  • express.urlencoded() – Form data parser

  • express.static() – Serve static files

Example Custom Middleware


πŸ“ Serving Static Files

Create a /public folder then:

Now your images, CSS, JS files load automatically.


🧭 Express Router (Modular Routing)

Create routes/user.js:


 

Use it in main file:

Visit:

/users
/users/profile

πŸ—„οΈ Connecting Express with Databases

Express works with any DB:

MongoDB (Mongoose)

npm install mongoose

MySQL

npm install mysql2

PostgreSQL

npm install pg

πŸ› οΈ Error Handling in Express

Express has a special error middleware:


πŸ” Express.js Security Best Practices

Install Helmet:

npm install helmet

Use middleware:

app.use(helmet());

πŸ“‘ Express with Nodemon (Auto Restart)

Install:

npm install --save-dev nodemon

Add script:

"start": "nodemon app.js"

Run:

npm start

πŸ“˜ Common Express.js Features

Feature Description
Routing Handle HTTP requests
Middleware Modify req/res
Static files Serve HTML, images, CSS
Templates EJS, Pug, Handlebars
REST APIs Build backend APIs
Error handling Custom error middleware

You may also like...