Getting Started with Express js

Getting Started with Express js

Introduction to Express.js

  • Express.js is a fast, minimalistic framework for Node.js that simplifies handling HTTP requests and responses.

  • Before Express, developers used the built-in http module in Node.js to create servers, which required extensive manual handling of routes, methods (GET, POST, etc.), and request parsing.

Problems with the Native http Module

  1. Complex Route Handling – Each new route must be manually defined and handled.

  2. Multiple HTTP Methods – Handling different methods (GET, POST, PUT, DELETE) requires additional conditions.

  3. Middleware Complexity – Parsing request parameters, headers, and body data requires extra modules.

  4. Boilerplate Code – Developers need to write extensive code for fundamental server functionality.

How Express Solves These Problems

  • Express abstracts away many complexities by providing an intuitive API for defining routes, handling middleware, and managing request-response cycles.

  • It allows defining routes for different HTTP methods in a clean and structured way.

Setting Up Express.js

1. Installing Express

Run the following command in the project directory:

npm install express

This installs Express and adds it as a dependency in package.json.

2. Importing and Initializing Express

In a new JavaScript file (e.g., server.js):

const express = require('express'); // Import Express
const app = express(); // Initialize the Express application

3. Creating Basic Routes

Express makes it easy to define routes with specific request methods:

app.get('/', (req, res) => {
    res.send('Hello from Home Page');
});

app.get('/about', (req, res) => {
    res.send('Hello from About Page');
});
  • app.get() handles GET requests for a specific path (/, /about).

  • The callback function takes request (req) and response (res) objects.

  • res.send() sends a response to the client.

4. Running the Server

To make the server listen for requests:

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
  • The listen() method starts the server on the specified port (3000).

  • The callback function logs a message when the server starts.

Key Advantages of Express

Simplifies Routing – Routes are easy to define and manage.
Middleware Support – Easily add middleware for parsing requests, authentication, etc.
Minimal Boilerplate Code – Reduces the amount of repetitive code needed.
Scalability – Ideal for small and large-scale applications.

Conclusion

Express.js makes backend development in Node.js easier, faster, and more efficient. It eliminates the complexities of the native http module by providing a clean, structured way to handle requests, responses, and middleware.