Routing is a fundamental concept in web development that involves determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, etc.). In Node.js, routing is typically handled using frameworks like Express.js, which simplifies the process significantly.
Key Concepts
- Routes: Define the endpoints and the HTTP methods that your application will respond to.
- Route Handlers: Functions that are executed when a specific route is matched.
- Middleware: Functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.
Setting Up Routing in Node.js with Express
Step 1: Install Express
First, ensure you have Express installed in your project. If not, you can install it using npm:
Step 2: Create a Basic Express Application
Create a file named app.js
and set up a basic Express application:
const express = require('express'); const app = express(); const port = 3000; app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
Step 3: Define Routes
Add routes to handle different HTTP methods and paths. For example:
// GET request to the root URL (/) app.get('/', (req, res) => { res.send('Hello, World!'); }); // GET request to /about app.get('/about', (req, res) => { res.send('About Us'); }); // POST request to /contact app.post('/contact', (req, res) => { res.send('Contact Us'); });
Step 4: Route Parameters
You can define route parameters to capture values in the URL:
// GET request with a route parameter app.get('/user/:id', (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`); });
Step 5: Query Parameters
Handle query parameters using req.query
:
// GET request with query parameters app.get('/search', (req, res) => { const query = req.query.q; res.send(`Search Query: ${query}`); });
Step 6: Using Middleware
Middleware functions can be used to handle requests before they reach the route handlers:
// Middleware to log request details app.use((req, res, next) => { console.log(`${req.method} request for '${req.url}'`); next(); }); // Route handler app.get('/', (req, res) => { res.send('Hello, World!'); });
Practical Example
Let's create a small application with multiple routes and middleware:
const express = require('express'); const app = express(); const port = 3000; // Middleware to log request details app.use((req, res, next) => { console.log(`${req.method} request for '${req.url}'`); next(); }); // Home route app.get('/', (req, res) => { res.send('Welcome to the Home Page'); }); // About route app.get('/about', (req, res) => { res.send('About Us'); }); // User route with parameter app.get('/user/:id', (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`); }); // Search route with query parameter app.get('/search', (req, res) => { const query = req.query.q; res.send(`Search Query: ${query}`); }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
Exercises
Exercise 1: Create a New Route
- Add a new route
/services
that responds with a list of services. - Add a new route
/contact
that responds with a contact form (just a simple message for now).
Solution
// Services route app.get('/services', (req, res) => { res.send('Our Services: Web Development, Mobile App Development, SEO'); }); // Contact route app.get('/contact', (req, res) => { res.send('Contact Us at [email protected]'); });
Exercise 2: Route with Parameters
- Create a route
/product/:id
that responds with the product ID. - Create a route
/category/:name
that responds with the category name.
Solution
// Product route with parameter app.get('/product/:id', (req, res) => { const productId = req.params.id; res.send(`Product ID: ${productId}`); }); // Category route with parameter app.get('/category/:name', (req, res) => { const categoryName = req.params.name; res.send(`Category: ${categoryName}`); });
Common Mistakes and Tips
- Forgetting to call
next()
in middleware: Always callnext()
to pass control to the next middleware or route handler. - Order of routes: Ensure that more specific routes are defined before more general ones to avoid unexpected behavior.
- Error handling: Use middleware to handle errors and send appropriate responses.
Conclusion
Routing is a crucial part of building web applications with Node.js and Express. By understanding how to define routes, handle parameters, and use middleware, you can create robust and scalable applications. In the next module, we will dive deeper into handling HTTP requests and responses, which will further enhance your ability to build dynamic web 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