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:
Install Express:
π§© Simple Express Server (Hello World)
Run:
Visit in browser:
π£οΈ 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:
ποΈ Connecting Express with Databases
Express works with any DB:
MongoDB (Mongoose)
MySQL
PostgreSQL
π οΈ Error Handling in Express
Express has a special error middleware:
π Express.js Security Best Practices
Install Helmet:
Use middleware:
π‘ Express with Nodemon (Auto Restart)
Install:
Add script:
Run:
π 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 |
