Lesson 1: Key Concepts of NodeJS and Express for Backend Web Development
Introduction to Node.js:
What is Node.js? An open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside a browser.
Why Node.js for Backend?
Non-blocking, event-driven architecture for efficient performance.
Single language (JavaScript) for both frontend and backend.
Large ecosystem via npm (Node Package Manager).
Core Concepts in Node.js:
Event Loop: Handles asynchronous operations.
Modules: Built-in (fs, http) and custom modules.
npm Packages: Managing dependencies using
package.json
.
Introduction to Express:
What is Express? A minimal and flexible Node.js web application framework.
Features:
Simplifies routing and middleware management.
Facilitates REST API development.
Easily integrates with databases.
2. Building Web Applications with Express:
Setting Up an Express Application:
Initialize Node Project:
mkdir express-app && cd express-app npm init -y npm install express
Create a Basic Server:
Create
index.js
:const express = require('express'); const app = express(); const PORT = 3000; app.get('/', (req, res) => { res.send('Hello, World!'); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
Run the Server:
node index.js
Visit
http://localhost:3000
in your browser to see "Hello, World!"
Routing in Express:
Define Routes:
app.get('/about', (req, res) => { res.send('About Page'); }); app.post('/contact', (req, res) => { res.send('Contact Form Submitted'); });
Middleware in Express:
Using Middleware:
app.use(express.json()); // To parse JSON bodies app.use((req, res, next) => { console.log(`${req.method} request for '${req.url}'`); next(); });
3. REST API Development with Express:
Create a Simple REST API:
Sample Data:
let users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, ];
CRUD Operations:
GET (Retrieve All Users):
app.get('/users', (req, res) => { res.json(users); });
GET (Retrieve Single User):
app.get('/users/:id', (req, res) => { const user = users.find(u => u.id == req.params.id); if (user) res.json(user); else res.status(404).send('User not found'); });
POST (Add New User):
app.post('/users', (req, res) => { const newUser = { id: users.length + 1, ...req.body }; users.push(newUser); res.status(201).json(newUser); });
PUT (Update User):
app.put('/users/:id', (req, res) => { const index = users.findIndex(u => u.id == req.params.id); if (index !== -1) { users[index] = { id: parseInt(req.params.id), ...req.body }; res.json(users[index]); } else res.status(404).send('User not found'); });
DELETE (Remove User):
app.delete('/users/:id', (req, res) => { users = users.filter(u => u.id != req.params.id); res.status(204).send(); });
Last updated