What is Express.js?

Express.js is a popular Node.js web application framework. It is known for its minimal and flexible nature. To build robust web applications, it’s essential to grasp its fundamental components. Let’s break down these components in a straightforward manner:

Also read: How To Create Node.js Apps On Android? : Termux.

1. App Object:

  • Core of the Application: This is the central object created using the express() function. It’s the foundation of your Express app.
  • Routing and Middleware: It’s responsible for handling routes (URLs) and middleware functions.

2. Middleware:

  • Functions Executed Between Requests and Responses: These are functions that are executed between the request and response cycle.
  • Types of Middleware:
    • Application-level: Applied to all incoming requests.
    • Router-level: Applied to specific routes.
    • Error-handling: Handles errors and sends appropriate responses.
  • Common Use Cases:
    • Logging requests.
    • Parsing request bodies (e.g., JSON, URL-encoded data).
    • Authenticating users.
    • Serving static files.

3. Routes:

  • Defining URL Patterns and Handlers: Routes specify the URL patterns that the app can handle and the corresponding functions (handlers) to execute when those patterns match.
  • HTTP Methods: Routes can be associated with different HTTP methods (GET, POST, PUT, DELETE, etc.) to handle various types of requests.
  • Route Parameters: Routes can include dynamic segments (parameters) to handle different URLs with the same pattern.

4. Request and Response Objects:

  • Representing Client Requests and Server Responses:
    • Request Object: Contains information about the incoming request, such as HTTP method, URL, headers, and body.
    • Response Object: Provides methods to send responses to the client, including setting headers, status codes, and the response body.

5. Templating Engines:

  • Rendering Dynamic HTML Content: While not strictly part of Express, templating engines are often used to generate dynamic HTML content based on data.
  • Popular Options: EJS, Pug (Jade), Handlebars.

6. Error Handling:

  • Gracefully Handling Exceptions: Express provides mechanisms to handle errors that occur during the request-response cycle.
  • Error Middleware: Specialized middleware functions can be used to catch errors and send appropriate responses to the client.

Example: Express.js

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

// Middleware 
app.use(express.json()); // Parse JSON request bodies 

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

// Error handling 
app.use((err, req, res, next) => { 
    res.status(500).send('Something went wrong!'); 
}); 

app.listen(3000, () => { 
    console.log('Server listening on port 3000'); 
});

Conclusion

Thank you for reading. In next post we will explore more about express.js app.