Express.js Fundamentals

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It's the standard for building servers in Node.

Why Express? While Node's native HTTP module is great, Express simplifies routing, middleware handling, and request/response management significantly.

1. Installation

To use Express, you first need to install it via NPM:

npm install express

2. Basic "Hello World" Server

Creating a server in Express is straightforward. You initialize an app, define a route, and start the listener.

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

// Define a GET route
app.get('/', (req, res) => {
  res.send('Hello from Express.js!');
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

3. Key Concepts

  • The App Object: Created by express(), it's the heart of your application.
  • Request Object (req): Contains info about the HTTP request (params, body, headers).
  • Response Object (res): Used to send data back to the client (json, html, status codes).
  • Routing: Determining which code to run for a specific URL.

4. Features of Express

Express makes it easy to:

  1. Write handlers for requests with different HTTP verbs at different URL paths.
  2. Integrate with "view" rendering engines in order to generate responses by inserting data into templates.
  3. Set common web application settings like the port to use for connecting, and the location of templates that are used for rendering the response.
  4. Add additional request processing "middleware" at any point within the request handling pipeline.