How to Create Routes in Express: A Complete Tutorial
Express is a minimal and flexible Node.js web application framework that provides robust features for building web applications and APIs. One of its core functionalities is routing, which helps manage how the application responds to client requests for different endpoints (URIs). This tutorial will guide you step-by-step on how to create routes in Express, from basic setup to using Express Router for modular route management.
Prerequisites
- Basic knowledge of JavaScript and Node.js.
- Node.js and npm installed on your machine. You can download Node.js from the official Node.js website.
- Code editor like Visual Studio Code.
- Terminal or command prompt access.
Step 1: Setup Your Express Project
Start by creating a new directory for your Express project and initialize it:
mkdir express-routing-tutorial
cd express-routing-tutorial
npm init -y
Install Express using npm:
npm install express
Step 2: Create Your Basic Express Server
Create a file named app.js and add the following code to set up a basic Express server:
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 Basic Routes
Routes define application endpoints and how they respond to client requests. Add a simple route in your app.js:
app.get('/', (req, res) => {
res.send('Welcome to the Home Page!');
});
app.get('/about', (req, res) => {
res.send('About Us Page');
});
This handles GET requests made to / and /about URLs.
Step 4: Handle Different HTTP Methods
You can handle POST, PUT, DELETE, and other HTTP methods similarly.
app.post('/submit', (req, res) => {
res.send('Form submitted!');
});
Step 5: Using Express Router for Modular Routes
For better organization in large applications, use express.Router() to create modular route handlers.
- Create a folder named
routes - Create a file
routes/users.jswith:
const express = require('express');
const router = express.Router();
// GET /users/
router.get('/', (req, res) => {
res.send('Users home page');
});
// GET /users/profile
router.get('/profile', (req, res) => {
res.send('User profile page');
});
module.exports = router;
Then, in app.js, import and use the router:
const userRoutes = require('./routes/users');
app.use('/users', userRoutes);
Step 6: Route Parameters and Query Strings
Express lets you handle dynamic routes using parameters:
app.get('/products/:productId', (req, res) => {
const productId = req.params.productId;
res.send(`Product ID requested: ${productId}`);
});
You can also handle query parameters like ?sort=desc via req.query:
app.get('/search', (req, res) => {
const searchTerm = req.query.q;
res.send(`Search results for: ${searchTerm}`);
});
Troubleshooting Common Issues
- Server not starting: Make sure you have installed Express and saved your
app.jsfile correctly. - Routes not responding: Check route paths and HTTP methods. Order of route declarations matters in Express.
- Modular routes not working: Ensure you exported and imported the router correctly and used
app.use(). - Port conflicts: Change the port number if the default (3000) is already in use.
Summary Checklist
- Set up Express and Node.js project
- Created basic Express server and routes
- Handled different HTTP methods (GET, POST)
- Used Express Router for modular route management
- Implemented route parameters and query string handling
- Troubleshot common routing issues
For more advanced Express tutorials, check out our article on How to Install Node.js Express: A Step-by-Step Guide to complement your routing knowledge.
Start building your app’s routing structure now to create scalable and maintainable Node.js applications with Express!
