Introduction to Express.js
Think of Express.js as a traffic controller for your web application. Just as a traffic controller directs vehicles to their proper destinations, Express.js directs web requests to the correct parts of your application. It's like having a skilled receptionist who knows exactly where to send each visitor in a large office building.
Before we dive in, let's understand why Express.js is so popular:
- It's minimalist yet powerful - like a Swiss Army knife for web development
- It's highly flexible - similar to building with LEGO blocks
- It has a gentle learning curve - perfect for beginners
Project Setup
Let's create a project called "coffee_shop_api" - imagine we're building an API for a local coffee shop. First, create your project structure:
coffee_shop_api/
├── node_modules/
├── routes/
│ ├── menu.js
│ └── orders.js
├── app.js
└── package.json
Initial Setup Steps
Open your terminal and follow these commands:
mkdir coffee_shop_api
cd coffee_shop_api
npm init -y
npm install express
Think of npm init as setting up your kitchen before cooking - it creates your package.json file, which is like your recipe book and inventory list combined.
Creating Your First Express Application
In your app.js file, write your first Express application:
// app.js
const express = require('express');
const app = express();
const port = 3000;
// Middleware for parsing JSON - like a translator for your API
app.use(express.json());
// Basic route - like a welcome mat for your application
app.get('/', (req, res) => {
res.send('Welcome to Coffee Shop API!');
});
// Start the server
app.listen(port, () => {
console.log(`Coffee Shop API is serving on port ${port}`);
});
Let's break this down:
- require('express') is like importing your chief assistant
- express() creates your application - think of it as opening your shop
- app.use(express.json()) is like hiring a translator who understands JSON
- app.get('/') is like creating your shop's front door
Setting Up Routers
Routers are like department managers in your coffee shop. They handle specific areas of responsibility. Let's create two routers: one for the menu and one for orders.
Menu Router
Create a new file: routes/menu.js
// routes/menu.js
const express = require('express');
const router = express.Router();
// Get all menu items
router.get('/', (req, res) => {
res.json({
items: [
{ id: 1, name: 'Espresso', price: 2.50 },
{ id: 2, name: 'Latte', price: 3.50 },
{ id: 3, name: 'Cappuccino', price: 3.00 }
]
});
});
// Get specific menu item
router.get('/:id', (req, res) => {
// The :id is like a variable in your route
const itemId = req.params.id;
res.json({ id: itemId, name: 'Espresso', price: 2.50 });
});
module.exports = router;
Orders Router
Create another file: routes/orders.js
// routes/orders.js
const express = require('express');
const router = express.Router();
// Create new order
router.post('/', (req, res) => {
const order = req.body;
// In a real app, you'd save this to a database
res.json({
message: 'Order received',
orderId: Date.now(),
order: order
});
});
// Get order status
router.get('/:orderId', (req, res) => {
const orderId = req.params.orderId;
res.json({
orderId: orderId,
status: 'preparing'
});
});
module.exports = router;
Connecting Routers to Your Application
Now, update your app.js to use these routers:
// app.js
const express = require('express');
const menuRouter = require('./routes/menu');
const ordersRouter = require('./routes/orders');
const app = express();
const port = 3000;
app.use(express.json());
// Connect routers - like assigning managers to their departments
app.use('/menu', menuRouter);
app.use('/orders', ordersRouter);
app.get('/', (req, res) => {
res.send('Welcome to Coffee Shop API!');
});
app.listen(port, () => {
console.log(`Coffee Shop API is serving on port ${port}`);
});
Testing Your API
Start your server and test these endpoints:
npm start # or node app.js
# Test with curl or Postman:
GET http://localhost:3000/menu
GET http://localhost:3000/menu/1
POST http://localhost:3000/orders
GET http://localhost:3000/orders/123
Real-World Applications
This pattern is used in many real-world scenarios:
- E-commerce platforms: Separate routers for products, cart, and user management
- Social media apps: Different routers for posts, users, and messages
- Banking applications: Separate routers for accounts, transactions, and user profiles
Exercises to Try
Practice by adding these features to your coffee shop API:
- Add a new router for managing customer loyalty points
- Create endpoints for special daily offers
- Implement a router for handling customer feedback
Next Steps
To deepen your Express.js knowledge, explore:
- Middleware creation and usage
- Error handling and validation
- Database integration (MongoDB, PostgreSQL)
- Authentication and authorization