Express Key Notes

1/1/1970

Express Key Notes

req & res objects

req (request) and res (response) are objects automatically provided by express when handling HTTP requests.

req (Request Object): Contains details about the incoming request. - req.query – Query parameters (/user?id=1) - req.params – Route parameters (/user/:id) - req.body – Request body (POST/PUT) - req.headers – HTTP headers res (Response Object): Used to send data back to the client. - res.send() – Send text/HTML/JSON - res.json() – Send JSON data - res.sendFile() – Send a file - res.status() – Set HTTP status code


Express Middleware

Middleware in Express is a function that has access to the request (req) and response (res) objects, and the next function (next) in the application’s request-response cycle.

Middleware Functions

Order of Middleware

Types of Middleware

  1. Application-Level Middleware: Applies to all routes or specific routes.
app.use((req, res, next) => {
  console.log('Request made!');
  next();  // Pass control to the next middleware
});
  1. Route-Level Middleware: Bound to specific routes.
app.get('/about', (req, res, next) => {
  console.log('Accessing About Page');
  next(); // Pass control to the route handler
});
  1. Error-Handling Middleware: This type of middleware is used to handle errors.
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
});
  1. Built-in Middleware: Express has built-in middleware like -express.json(), express.urlencoded(), express.static(), express.Router()
app.use(express.static('public'));  // Serve static files from the 'public' folder
  1. Third-Party Middleware: Middleware from external packages (e.g., morgan for logging, cors for handling cross-origin requests).

Express Route Methods and Middleware

app.use() : Used to apply middleware functions that run on every request or specific routes.

app.use([path], middleware); // path is optinal

app.get() : Defines a route handler for GET requests at a specified URL path.

app.get(path, middleware, callback);

app.post() : Defines a route handler for POST requests at a specified URL path.

app.post(path, middleware, callback);

app.put() : Defines a route handler for PUT requests at a specified URL path.

app.put(path, middleware, callback);

app.delete() : Defines a route handler for DELETE requests at a specified URL path.

app.delete(path, middleware, callback);

Note: Square brackets [] are used in documentation or examples to indicate optional parameters, but in this case, the middleware itself is required to be a function.

Conclusion:


Difference Between Middleware and Route Handler

// Middleware
const midd = (req, res, next) => { ... };
// Route Handler (sends the response)
app.get('/', myMiddleware, (req, res) => {...}
);

Note: In Express.js, the route handler is a callback function that processes a specific route.


Static(Public) vs Template Directory

static / public folder

template folder


express() vs express

express() : creates an instance of an Express application.

const app = express(); // Creates an Express 
 
app.use(...) // Use instance of `express()`

express : express module

const express = require('express');  // Import the Express module
 
express.static() // use 'static()' middleware of express module