Express.js – Beginner to Pro Guide

Build RESTful APIs easily with Node.js & Express

📌 What is Express.js?

Definition: Express.js is a fast, unopinionated, minimalist web framework for Node.js. It simplifies building web applications and APIs.

❓ Why Use Express.js?

⚙️ How to Install

Install Express in your Node.js project:

npm init -y
npm install express

📆 When to Use

Use Express when your project requires:

💡 Basic Example

Create index.js file with this code:

Know Behind the express()
const express = require('express');
const app = express();
const PORT = 3000;

// Middleware to parse JSON
app.use(express.json());

// Root route
app.get('/', (req, res) => {
  res.send('Welcome to Express.js API!');
});

// Example POST route
app.post('/user', (req, res) => {
  const user = req.body;
  res.json({ message: 'User created', user });
});

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

🔧 Middleware Example

Log every incoming request:

app.use((req, res, next) => {
  console.log(\`\${req.method} request to \${req.url}\`);
  next();
});

❌ Error Handling

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});