Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Express.js Routing

Express.js provides a robust routing mechanism that allows you to define application endpoints and handle HTTP requests. This guide covers key concepts, examples, and best practices for using routing in Express.js.

Key Concepts of Express.js Routing

  • Route: A defined endpoint (URI) that responds to client requests.
  • HTTP Methods: Different types of requests (GET, POST, PUT, DELETE, etc.) that a route can handle.
  • Route Parameters: Variables in route paths that capture values from the URL.
  • Middleware: Functions that execute during the request-response cycle.

Creating Routes

Use the app.get, app.post, app.put, and app.delete methods to create routes for different HTTP methods:

Example: Basic Routes

// app.js
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.send('Hello, World!');
});

app.get('/about', (req, res) => {
    res.send('About Page');
});

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');
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Using Route Parameters

Define route parameters to capture values from the URL:

Example: Route Parameters

// params.js
const express = require('express');
const app = express();
const port = 3000;

app.get('/user/:id', (req, res) => {
    res.send(`User ID: ${req.params.id}`);
});

app.get('/post/:postId/comment/:commentId', (req, res) => {
    res.send(`Post ID: ${req.params.postId}, Comment ID: ${req.params.commentId}`);
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Using Query Parameters

Capture query parameters from the URL using req.query:

Example: Query Parameters

// query.js
const express = require('express');
const app = express();
const port = 3000;

app.get('/search', (req, res) => {
    const { term, sort } = req.query;
    res.send(`Search Term: ${term}, Sort By: ${sort}`);
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Using Middleware for Routing

Apply middleware to specific routes or route groups:

Example: Middleware for Routing

// middleware-routes.js
const express = require('express');
const app = express();
const port = 3000;

// Middleware function
const logger = (req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
};

// Apply middleware to specific route
app.get('/about', logger, (req, res) => {
    res.send('About Page with Logger');
});

// Apply middleware to all routes
app.use(logger);

app.get('/', (req, res) => {
    res.send('Hello, World!');
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Using Express Router

Use the express.Router class to create modular, mountable route handlers:

Example: Using Express Router

// router.js
const express = require('express');
const app = express();
const port = 3000;
const router = express.Router();

// Define routes
router.get('/', (req, res) => {
    res.send('Home Page');
});

router.get('/about', (req, res) => {
    res.send('About Page');
});

// Use router
app.use('/', router);

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Best Practices for Express.js Routing

  • Organize Routes: Group related routes using the express.Router class for better maintainability.
  • Use Middleware: Leverage middleware for common tasks such as logging, authentication, and error handling.
  • Validate Inputs: Validate and sanitize route and query parameters to prevent security vulnerabilities.
  • Handle Errors: Implement robust error handling to manage runtime exceptions and send appropriate responses.
  • RESTful Design: Follow RESTful principles when designing your routes to ensure consistency and scalability.

Testing Express.js Routes

Test your Express.js routes using frameworks like Mocha, Chai, and Supertest:

Example: Testing Routes with Mocha, Chai, and Supertest

// Install Mocha, Chai, and Supertest
// npm install --save-dev mocha chai supertest

// test/routes.test.js
const chai = require('chai');
const expect = chai.expect;
const request = require('supertest');
const express = require('express');

const app = express();
app.get('/', (req, res) => {
    res.send('Hello, World!');
});

app.get('/user/:id', (req, res) => {
    res.send(`User ID: ${req.params.id}`);
});

describe('GET /', () => {
    it('should respond with "Hello, World!"', (done) => {
        request(app)
            .get('/')
            .expect('Content-Type', /text\/html/)
            .expect(200, 'Hello, World!', done);
    });
});

describe('GET /user/:id', () => {
    it('should respond with User ID', (done) => {
        request(app)
            .get('/user/123')
            .expect('Content-Type', /text\/html/)
            .expect(200, 'User ID: 123', done);
    });
});

// Define test script in package.json
// "scripts": {
//   "test": "mocha"
// }

// Run tests with NPM
// npm run test

Key Points

  • Route: A defined endpoint (URI) that responds to client requests.
  • HTTP Methods: Different types of requests (GET, POST, PUT, DELETE, etc.) that a route can handle.
  • Route Parameters: Variables in route paths that capture values from the URL.
  • Follow best practices for routing in Express.js, such as organizing routes, using middleware, validating inputs, handling errors, and following RESTful design principles.

Conclusion

Express.js provides a robust routing mechanism that allows you to define application endpoints and handle HTTP requests. By understanding and implementing the key concepts, examples, and best practices covered in this guide, you can effectively use routing in your Express.js applications. Happy coding!