Express.js Basics Routing

In the world of web development, routing is essentially the traffic controller of your application. It determines how your server responds to a client request for a specific endpoint (a URI or path) and a specific HTTP request method (GET, POST, and so on). In Express.js, routing is highly intuitive, allowing you to map URLs to specific functions that handle your business logic and return data to the user.

Developer Tip: Think of a route as a combination of a Path (the URL) and a Method (the action). Without both, Express won't know exactly what you want to do.

 

Key Features of Routing in Express.js

  • Route Definition: Routes are created using methods of the Express app object that correspond to HTTP methods. For example, app.get() handles GET requests (reading data), while app.post() handles POST requests (creating data).
  • Dynamic Routes: Real-world apps rarely have static URLs for everything. Express allows you to use route parameters to capture values at specific positions in the URL, such as a user ID or a product slug.
  • Middleware Support: Express allows you to "plug in" functions between the request and the response. This is perfect for checking if a user is logged in or for logging incoming requests to the console.
Best Practice: Always use nouns for your route paths (e.g., /users or /products) rather than verbs (e.g., /getUsers). The HTTP method itself (GET, POST, DELETE) acts as the verb.

 

Steps to Define Basic Routes in Express.js

Set up a Basic Express Application
To get started, you need to initialize your Node.js environment. Open your terminal in a new folder and run:

npm init -y
npm install express --save

Create a Basic Express Application
Create a file named app.js. This will be the entry point for your server. Copy the following code to see how different route types look in practice:

const express = require('express');
const app = express();

// Define a simple route for the home page
app.get('/', (req, res) => {
    res.send('Hello, Express!');
});

// Define a route for the "about" page
app.get('/about', (req, res) => {
    res.send('This is the About page');
});

// Define a route with a dynamic parameter
app.get('/user/:id', (req, res) => {
    const userId = req.params.id;
    res.send(`User ID: ${userId}`);
});

// Define a POST route for form submission
app.post('/submit', (req, res) => {
    res.send('Form Submitted!');
});

// Start the server
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});
Common Mistake: Forgetting to send a response back to the client. If you don't call res.send(), res.json(), or res.end(), the client (like a browser) will keep waiting until it eventually times out.

Run the Application
To launch your server, execute this command in your terminal:

node app.js

Test the Routes
You can test your GET routes directly in any web browser, but for POST, PUT, and DELETE, you'll need a tool like Postman, Insomnia, or the cURL command line.

  • http://localhost:3000/ – You should see "Hello, Express!"
  • http://localhost:3000/about – You should see "This is the About page"
  • http://localhost:3000/user/123 – The browser will display "User ID: 123". This demonstrates how :id acts as a variable.
  • To test the /submit route, send a POST request via Postman to http://localhost:3000/submit.
Watch Out: Route order matters! Express matches routes from top to bottom. If you have a route /user/profile and a dynamic route /user/:id, and you place the dynamic one first, /user/profile might never be reached because "profile" will be captured as the "id".

Route Handling for Multiple Methods
Sometimes, a single URL needs to handle different actions. For example, a /product page might allow a user to view a product (GET) and an admin to update it (PUT). You can chain these using app.route() to keep your code clean and DRY (Don't Repeat Yourself):

app.route('/product')
    .get((req, res) => {
        res.send('Fetching product details...');
    })
    .post((req, res) => {
        res.send('Creating a new product...');
    })
    .put((req, res) => {
        res.send('Updating an existing product...');
    });

Using Query Parameters
Query parameters are the key-value pairs found after the ? in a URL. They are commonly used for filtering or searching. In Express, these are automatically parsed into the req.query object.

app.get('/search', (req, res) => {
    const searchTerm = req.query.q;
    const sortBy = req.query.sort;
    res.send(`Search results for: ${searchTerm}, sorted by: ${sortBy}`);
});

If you visit http://localhost:3000/search?q=express&sort=asc, the response will be: Search results for: express, sorted by: asc.

Developer Tip: Use Route Parameters (/user/:id) for identifying a specific resource and Query Parameters (?search=term) for filtering or sorting a list of resources.

 

Summary

Express.js routing is the backbone of any Node.js web application. By combining HTTP methods with static and dynamic paths, you can build complex APIs and websites with very little code. Remember that Express handles routes in the order they are defined, and always ensure every route ends by sending a response back to the user. With these basics mastered, you are ready to start building functional web services!