What is Express.js?
Express.js is a powerful and flexible web application framework for Node.js. It simplifies the process of building web applications and APIs by providing a robust set of features and tools. Here's a breakdown of the key aspects of Express.js:
- Routing: Express allows you to define routes for handling different HTTP requests (GET, POST, PUT, DELETE, etc.) on specific URLs. This makes it easy to create organized and structured APIs and web applications.
- Middleware: Express uses middleware functions to perform tasks such as parsing incoming requests, logging, authentication, and more. Middleware functions have access to the request and response objects and can modify them as needed.
- Templating Engines: Express supports various templating engines like EJS, Pug, Handlebars, etc., making it simple to generate dynamic HTML content.
- Error Handling: Express provides built-in error handling mechanisms to catch and handle errors that occur during the execution of your application.
Now, let's dive into the basics of Express.js using the provided code:
const express = require('express')
const app = express()
// app.get
app.get('/', (req, res) => {
console.log('user hit the resource')
res.status(200).send('Home Page')
})
// app.get for About Page
app.get('/about', (req, res) => {
res.status(200).send('About Page')
})
// app.all
app.all('*', (req, res) => {
res.status(404).send('<h1>resource not found</h1>')
})
// app.listen
app.listen(5000, () => {
console.log('server is listening on port 5000...')
})
Explaining the Commented Parts:
- app.get: Defines a route for handling GET requests to the root URL / and sends back a response with the message 'Home Page'.
- app.post, app.put, app.delete: These are other HTTP methods that can be used to define routes for handling POST, PUT, and DELETE requests respectively.
- app.all: This method is used to handle all HTTP methods (GET, POST, PUT, DELETE, etc.) for a specific route ('*' represents all routes). In this example, it handles any other route that hasn't been defined, sending a 404 Not Found response.
- app.listen: Starts the Express server and listens on port 5000. When the server starts, it logs a message 'server is listening on port 5000...'.
Why Express.js?
Now, let's compare the Express.js approach with the traditional Node.js HTTP server approach:
const http = require("http");
const { readFileSync } = require("fs");
const server = http.createServer((req, res) => {
const url = req.url;
if (url === "/") {
// Send HTML file
} else if (url === "/about") {
// Send About Page HTML
} else if (url === "/styles.css") {
// Send CSS file
} else if (url === "/logo.svg") {
// Send SVG image
} else if (url === "/browser-app.js") {
// Send JavaScript file
} else {
// Handle 404 - Page not Found
}
});
server.listen(5000);
In the traditional approach:
- We manually handle each route and its corresponding response logic.
- We need to manually set the content type for each response.
- The code can become lengthy and less maintainable as the application grows.
Advantages of Express.js:
- Simplicity and Clean Code:Express provides a more intuitive and cleaner way to define routes and handle requests, leading to more readable and maintainable code.
- Middleware Functionality:The use of middleware simplifies tasks such as parsing request bodies, handling cookies, implementing authentication, and more.
- Route Handling:Express makes it easy to define routes for different HTTP methods, making the code more organized and structured.
- Error Handling:Built-in error handling in Express allows for centralized error handling, improving application robustness.
- Template Engines Support:Express supports various templating engines, allowing for dynamic generation of HTML content.
By using Express.js, developers can streamline the development process, enhance code readability, and build scalable and efficient web applications and APIs.