Express.js is a fast, minimal, and flexible Node.js web framework used to build APIs and web apps.
1οΈβ£ What is Express.js? ποΈ
A lightweight framework on top of Node.js that simplifies routing, middleware, request handling, and more.
2οΈβ£ Install Express: π¦
npm init -y
npm install express
3οΈβ£ Basic Server Setup: π
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello Express!');
});
app.listen(3000, () => console.log('Server running on port 3000'));4οΈβ£ Handling Different Routes: πΊοΈ
app.get('/about', (req, res) => res.send('About Page'));
app.post('/submit', (req, res) => res.send('Form submitted'));5οΈβ£ Middleware: βοΈ
Functions that run before a request reaches the route handler.
app.use(express.json()); // Example: Parse JSON body
6οΈβ£ Route Parameters & Query Strings: β
app.get('/user/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`); // Access route parameter
});
app.get('/search', (req, res) =>
res.send(`You searched for: ${req.query.q}`); // Access query string
);7οΈβ£ Serving Static Files: π
app.use(express.static('public')); // Serves files from the 'public' directory8οΈβ£ Sending JSON Response: π
app.get('/api', (req, res) => {
res.json({ message: 'Hello API' }); // Sends JSON response
});9οΈβ£ Error Handling: β οΈ
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error for debugging
res.status(500).send('Something broke!'); // Send a generic error response
});π Real Projects You Can Build: π
- RESTful APIs
- To-Do or Notes app backend
- Auth system (JWT)
- Blog backend with MongoDB
π‘ Tip: Master your tools to boost efficiency and build better web apps, faster.
π¬ Tap β€οΈ for more!