Routing is a fundamental concept in web development, and Express.js provides a robust and flexible way to handle routing in your Node.js applications. In this section, we will cover the basics of routing in Express, including defining routes, handling different HTTP methods, and organizing routes in a modular way.
Key Concepts
- Routes: Define the endpoints of your application and specify how to handle requests to those endpoints.
- HTTP Methods: Differentiate between various types of requests (GET, POST, PUT, DELETE, etc.).
- Route Parameters: Capture dynamic values from the URL.
- Middleware: Functions that execute during the lifecycle of a request to the server.
Defining Routes
In Express, routes are defined using the app
object. Here’s a basic example:
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello, World!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
Explanation
app.get('/')
: Defines a route that listens for GET requests on the root URL (/
).req
andres
: Represent the request and response objects, respectively.res.send('Hello, World!')
: Sends a response back to the client.
Handling Different HTTP Methods
Express allows you to handle different HTTP methods using corresponding functions like app.get()
, app.post()
, app.put()
, and app.delete()
.
app.post('/submit', (req, res) => { res.send('Form submitted!'); }); app.put('/update', (req, res) => { res.send('Data updated!'); }); app.delete('/delete', (req, res) => { res.send('Data deleted!'); });
Explanation
app.post('/submit')
: Handles POST requests to the/submit
endpoint.app.put('/update')
: Handles PUT requests to the/update
endpoint.app.delete('/delete')
: Handles DELETE requests to the/delete
endpoint.
Route Parameters
Route parameters allow you to capture values from the URL and use them in your route handlers.
app.get('/user/:id', (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`); });
Explanation
:id
: Defines a route parameter namedid
.req.params.id
: Accesses the value of theid
parameter from the URL.
Organizing Routes
As your application grows, it’s a good practice to organize your routes into separate files or modules. This makes your code more maintainable and easier to understand.
Example: Organizing Routes in a Separate File
- Create a new file
routes.js
:
const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.send('Home Page'); }); router.get('/about', (req, res) => { res.send('About Page'); }); module.exports = router;
- Use the routes in your main application file
app.js
:
const express = require('express'); const app = express(); const routes = require('./routes'); app.use('/', routes); app.listen(3000, () => { console.log('Server is running on port 3000'); });
Explanation
express.Router()
: Creates a new router object.router.get()
: Defines routes on the router object.app.use()
: Mounts the router on the specified path.
Practical Exercise
Task
Create an Express application with the following routes:
- A GET route at
/
that responds with "Welcome to the Home Page". - A GET route at
/users
that responds with "User List". - A GET route at
/users/:id
that responds with "User ID: [id]".
Solution
- Create a new file
app.js
:
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Welcome to the Home Page'); }); app.get('/users', (req, res) => { res.send('User List'); }); app.get('/users/:id', (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
Explanation
- The application defines three routes:
/
,/users
, and/users/:id
. - Each route sends a different response based on the URL and parameters.
Common Mistakes and Tips
- Forgetting to start the server: Always ensure you have
app.listen()
to start your server. - Incorrect HTTP methods: Make sure you use the correct method (
GET
,POST
, etc.) for the intended action. - Route order: Routes are matched in the order they are defined. More specific routes should be defined before more general ones.
Conclusion
In this section, we covered the basics of routing in Express, including defining routes, handling different HTTP methods, using route parameters, and organizing routes in a modular way. Understanding these concepts is crucial for building robust and maintainable web applications with Express.
Next, we will dive into error handling in Express, which is essential for creating reliable applications.
Node.js Course
Module 1: Introduction to Node.js
Module 2: Core Concepts
Module 3: File System and I/O
Module 4: HTTP and Web Servers
Module 5: NPM and Package Management
- Introduction to NPM
- Installing and Using Packages
- Creating and Publishing Packages
- Semantic Versioning
Module 6: Express.js Framework
- Introduction to Express.js
- Setting Up an Express Application
- Middleware
- Routing in Express
- Error Handling
Module 7: Databases and ORMs
- Introduction to Databases
- Using MongoDB with Mongoose
- Using SQL Databases with Sequelize
- CRUD Operations
Module 8: Authentication and Authorization
Module 9: Testing and Debugging
- Introduction to Testing
- Unit Testing with Mocha and Chai
- Integration Testing
- Debugging Node.js Applications
Module 10: Advanced Topics
Module 11: Deployment and DevOps
- Environment Variables
- Using PM2 for Process Management
- Deploying to Heroku
- Continuous Integration and Deployment