Code-Alongs are live experiences taught by expert instructors designed to prepare you for concepts found in the sprint challenges. These sessions are your opportunity to work on complex job-ready problems in a live and engaging environment.
The best Code-Along experiences happen when you are ready before coming to class. Your instructors create starting points and solutions for each Code-Along to ensure you have what you need to succeed.
Learn how to build and interact with APIs using Node.js and Express.
const express = require('express');
const server = express();
server.use(express.json());
// Mock database
let users = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' }
];
// GET all users
server.get('/api/users', (req, res) => {
res.status(200).json(users);
});
// GET user by ID
server.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ message: 'User not found' });
res.status(200).json(user);
});
// POST new user
server.post('/api/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name,
email: req.body.email
};
users.push(newUser);
res.status(201).json(newUser);
});
server.listen(5000, () => {
console.log('Server running on port 5000');
});
Explore middleware concepts and implementation in Express applications.
const express = require('express');
const server = express();
server.use(express.json());
// Logging middleware
const logger = (req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
next();
};
// Authentication middleware
const authenticate = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader || authHeader !== 'Bearer valid-token') {
return res.status(401).json({ message: 'Unauthorized' });
}
next();
};
// Apply logger middleware to all routes
server.use(logger);
// Public route
server.get('/api/public', (req, res) => {
res.json({ message: 'This is public data' });
});
// Protected route with authentication middleware
server.get('/api/protected', authenticate, (req, res) => {
res.json({ message: 'This is protected data' });
});
server.listen(5000, () => {
console.log('Server running on port 5000');
});