• What is Express.js?

    1. Express.js is a minimal and flexible Node.js web framework used to build web applications and APIs.

    2. Provides robust features like routing, middleware support, and template engines.

    3. Simplifies handling HTTP requests, responses, and server logic compared to plain Node.js.

    4. Often used with Node.js to build REST APIs, web apps, and microservices quickly.

      Tip to remember: Express.js = Node framework for easy routing, middleware, and server development

  • Why use Express with Node?

    1. Express.js simplifies Node.js development by providing easy routing, middleware support, and HTTP utilities.
    2. Benefits of using Express with Node:
      • Faster development with less boilerplate code

      • Middleware support for authentication, logging, error handling, etc.

      • Routing system to handle different endpoints efficiently

      • Flexible and minimal while allowing full customization

      • Works well with REST APIs and microservices

        Tip to remember: Express + Node = faster, structured, and flexible server-side development

  • What is routing?

    1. Routing is the process of defining how an application responds to client requests to specific URLs or endpoints.

    2. In Node.js/Express, routes determine which function or controller handles a request.

    3. Example in Express:

      const express = require('express');
      const app = express();
      
      app.get('/home', (req, res) => {
        res.send('Welcome Home!');
      });
      
      app.post('/login', (req, res) => {
        res.send('Login successful');
      });
      
    4. Routes can handle GET, POST, PUT, DELETE methods and can be grouped using routers.

      Tip to remember: Routing = map URLs and HTTP methods to functions that handle requests

  • Route parameters

    1. Route parameters are dynamic segments in a URL that allow routes to capture values from the URL itself.

    2. In Express, route parameters are prefixed with a : in the route path.

    3. Example:

      const express = require('express');
      const app = express();
      
      app.get('/user/:id', (req, res) => {
        res.send(`User ID is ${req.params.id}`);
      });
      
      app.listen(3000);
      
    4. req.params is used to access the values of route parameters.

      Tip to remember: Route parameters = dynamic URL parts captured using :paramName

  • Query parameters

    1. Query parameters are key-value pairs in a URL used to send optional data to the server.

    2. They appear after ? in the URL and are separated by &.

    3. Example:

      const express = require('express');
      const app = express();
      
      app.get('/search', (req, res) => {
        res.send(`Search query is ${req.query.q}`);
      });
      
      // URL: /search?q=nodejs&sort=asc
      // req.query = { q: 'nodejs', sort: 'asc' }
      
    4. req.query is used to access query parameters in Express.

      Tip to remember: Query parameters = optional key-value data in URL after ?

  • What is middleware?

    1. Middleware is a function in Express.js that has access to the request, response, and next() in the request-response cycle.

    2. Middleware can execute code, modify request/response, end the request, or pass control to the next middleware.

    3. Types of middleware:

      • Application-level → used across the app (app.use())
      • Router-level → used in specific routes (router.use())
      • Error-handling → handles errors ((err, req, res, next) => {})
      • Built-in → like express.json(), express.static()
      • Third-party → like cors, helmet, morgan
    4. Example:

      const express = require('express');
      const app = express();
      
      const logger = (req, res, next) => {
        console.log(`${req.method} ${req.url}`);
        next();
      };
      
      app.use(logger);
      app.get('/', (req, res) => res.send('Home Page'));
      

    Tip to remember: Middleware = functions that process requests before reaching the route or after

  • Types of middleware

    1. Application-level middleware → applied to the entire app using app.use() or app.METHOD().

      app.use((req, res, next) => { console.log('App-level middleware'); next(); });
      
    2. Router-level middleware → applied to specific routers or routes using router.use() or router.METHOD().

      const router = express.Router();
      router.use((req, res, next) => { console.log('Router-level middleware'); next(); });
      
    3. Error-handling middleware → handles errors in the app, defined with four parameters (err, req, res, next).

      app.use((err, req, res, next) => { res.status(500).send(err.message); });
      
    4. Built-in middleware → comes with Express, e.g., express.json(), express.urlencoded(), express.static().

    5. Third-party middleware → added via npm, e.g., cors, helmet, morgan.

    Tip to remember: Middleware types = Application, Router, Error, Built-in, Third-party

  • Error-handling middleware

    1. Error-handling middleware in Express is a special middleware that catches and handles errors occurring in routes or other middleware.

    2. It is defined with four parameters: (err, req, res, next).

    3. Example:

      const express = require('express');
      const app = express();
      
      app.get('/', (req, res) => {
        throw new Error('Something went wrong!');
      });
      
      app.use((err, req, res, next) => {
        console.error(err.stack);
        res.status(500).send({ error: err.message });
      });
      
      app.listen(3000);
      
    4. Benefits: centralized error handling, cleaner code, better debugging, and consistent responses.

    Tip to remember: Error-handling middleware = four-parameter function to catch and respond to errors

  • next() function

    1. next() function in Express is used to pass control from one middleware to the next in the request-response cycle.

    2. Without calling next(), the request will hang and not move to the next middleware or route.

    3. Example:

      const express = require('express');
      const app = express();
      
      const logger = (req, res, next) => {
        console.log(`${req.method} ${req.url}`);
        next(); // pass control to next middleware
      };
      
      app.use(logger);
      
      app.get('/', (req, res) => res.send('Home Page'));
      app.listen(3000);
      
    4. Also used in error-handling to pass errors to error middleware: next(err).

    Tip to remember: next() = move to next middleware or route in the chain

  • What is body-parser?

    1. Body-parser is a Node.js middleware used to parse incoming request bodies in middleware before your handlers, making it accessible via req.body.
    2. Handles JSON, URL-encoded, and raw form data sent from clients.
    3. Example in Express:
    4. In Express 4.16+, body-parser is built-in via express.json() and express.urlencoded().

    Tip to remember: Body-parser = middleware to read and parse request body data into req.body

  • What is express.json()?

  • What is app.use()?

  • Difference between app.get and router.get

  • What is Router?

  • Modular routing

  • What is RESTful API?

  • HTTP status codes

  • What is CORS?

  • How to enable CORS?

  • JWT authentication in Express