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!
#ExpressJS #NodeJS #WebDevelopment #Backend #API #JavaScript #Framework #Developer #Coding #TechSkills