Node Express
Introduction
Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It is a framework that sits on top of Node.js and helps in building web applications and APIs with ease.
Install Express -npm install express
Basic Example -
const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); });
Advantages -
i) Simplicity and Minimalism
Minimalist Framework: Express is minimal, providing only the essentials to get a web server up and running.
Learning Curve: The simplicity of Express makes it easy for beginners to understand and start building applications quickly.
ii) Flexibility
Middleware: Express allows the use of middleware functions to handle requests and responses, giving developers the flexibility to customize the application as needed.
Customizable: It does not enforce any strict structure, giving developers the freedom to structure their application as they see fit.
iii) Performance
Fast and Lightweight: Express is lightweight and fast, built on top of the performant Node.js runtime.
iv) Routing
Advanced Routing: Express provides a powerful routing mechanism that allows developers to handle different HTTP methods and URL patterns easily.
v) Middleware Support
Built-in and Third-party Middleware: Express supports both built-in and third-party middleware, making it easy to add functionalities like logging, authentication, and error handling.
vi) Scalability
Modular: The modular nature of Express allows developers to build scalable applications. They can easily add or remove features as needed.
Integration: Express integrates well with various databases and templating engines, allowing for scalable and maintainable code.
vii) Community and Ecosystem
Large Community: Express has a large and active community, providing a wealth of resources, tutorials, and third-party packages.
Ecosystem: Being a part of the Node.js ecosystem, Express benefits from the wide array of Node.js modules and tools available.
viii) Support for RESTful APIs
REST API Development: Express is commonly used to build RESTful APIs due to its straightforward approach to handling HTTP requests and responses.
ix) Testing
Ease of Testing: Express applications are easy to test using various testing frameworks like Mocha, Chai, and Jest.
x) Compatibility
Cross-platform: Express applications run on any platform that supports Node.js, making it a versatile choice for developers.Request and Response in Express
In Express, when handling HTTP requests, two crucial objects are passed to your route handler functions:req
(request) andres
(response). These objects provide essential information and methods to work with the incoming request and to send back a response to the client.
Thereq
object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and more.
i) req.params
Contains route parameters (in the path portion of the URL).
Example: For a route/user/:id
,req.params.id
will contain the value ofid
.app.get('/user/:id', (req, res) => { res.send(`User ID: ${req.params.id}`); });
ii) req.query
Contains the query string parameters (in the URL).
Example: For a URL/search?name=John
,req.query.name
will beJohn
.app.get('/search', (req, res) => { res.send(`Search query: ${req.query.name}`); });
iii) req.body
Contains the data sent in the request body.
This requires middleware likebody-parser
to parse JSON or URL-encoded data.const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.post('/profile', (req, res) => { res.send(`User name is: ${req.body.name}`); });
iv) req.headers
Contains the headers sent with the request.
Example:req.headers['content-type']
to get the content type of the request.app.get('/', (req, res) => { res.send(`Content-Type: ${req.headers['content-type']}`); });
v) req.method
The HTTP method used (GET, POST, etc.).app.use((req, res, next) => { console.log(`Request Method: ${req.method}`); next(); });
vi) req.url
The full URL of the request.app.use((req, res, next) => { console.log(`Request URL: ${req.url}`); next(); });
The
res
object represents the HTTP response that an Express app sends when it gets an HTTP request. It contains methods to send responses back to the client.
i) res.send()
Sends a response of various types (string, object, buffer).app.get('/', (req, res) => { res.send('Hello World'); });
ii) res.json()
Sends a JSON response.app.get('/user', (req, res) => { res.json({ name: 'John', age: 30 }); });
iii) res.status()
Sets the HTTP status code for the response.app.get('/not-found', (req, res) => { res.status(404).send('Not Found'); });
iv) res.sendFile()
Sends a file as an octet stream.const path = require('path'); app.get('/file', (req, res) => { res.sendFile(path.join(__dirname, 'file.txt')); });
v) res.redirect()
Redirects the client to a different URL.app.get('/google', (req, res) => { res.redirect('https://www.google.com'); });
vi) res.set()
Sets a response header.app.get('/', (req, res) => { res.set('Content-Type', 'text/plain'); res.send('Hello World'); });
Here’s an example demonstrating how to use
req
andres
:const express = require('express'); const app = express(); const port = 3000; app.use(express.json()); app.get('/user/:id', (req, res) => { const userId = req.params.id; const filter = req.query.filter; res.send(`User ID: ${userId}, Filter: ${filter}`); }); app.post('/user', (req, res) => { const userName = req.body.name; res.status(201).json({ message: `User ${userName} created` }); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
The
GET /user/:id
route extracts theid
from the URL and thefilter
from the query string.
ThePOST /user
route reads thename
from the request body and sends a JSON response with a 201 status code.