Node.js Masterclass
High-Performance Backends01.Home02.Introduction03.Environment Setup04.Modules & Exports05.File System (fs)06.Path & OS Modules07.Buffer & Streams08.Events & EventEmitter09.HTTP Module10.NPM & Package.json11.Express.js Fundamentals12.Express Routing13.Express Middleware14.RESTful API Development15.Asynchronous Programming16.Error Handling17.Database with Mongoose18.Authentication with JWT19.Environment Variables20.Testing with Jest21.Deployment & PM2
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 express2. 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:
- Write handlers for requests with different HTTP verbs at different URL paths.
- Integrate with "view" rendering engines in order to generate responses by inserting data into templates.
- Set common web application settings like the port to use for connecting, and the location of templates that are used for rendering the response.
- Add additional request processing "middleware" at any point within the request handling pipeline.