Site icon TechVidvan

Node.js Express Framework

node js express framework

Express is a popular open-source web application framework for Node.js, used to build server-side web applications. It provides a simple and flexible API for building web applications, allowing developers to create high-performance and scalable web applications with ease.

Express was first released in 2010 and has since become one of the most widely used frameworks for Node.js. It has a large and active community of developers, and a vast ecosystem of modules and tools that can be used to extend its capabilities.

Key Features of Express

1. Middleware: Express provides middleware, which are functions that can be executed during the request-response cycle of an HTTP request. Middleware functions can be used to modify the request or response objects, perform authentication or validation, or handle errors.

2. Routing: Express provides a simple and flexible routing system that allows developers to define routes for different HTTP methods and URLs. Route handlers can be used to handle requests and send responses.

3. Template Engines: Express supports multiple template engines such as Pug, EJS, and Handlebars, which allow developers to easily generate HTML pages with dynamic content.

4. Error Handling: Express provides a robust error-handling mechanism that allows developers to handle errors in a central location and provide appropriate responses to clients.

Installing Express

To get started with Express, we need to install it as a dependency in our Node.js project. We can do this using the following command:

npm install express

Once we have installed Express, we can create a new Express application by creating a new JavaScript file and importing the Express module.

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

In the above code, we import the Express module and create a new Express application instance. We can then define routes for the application using the HTTP methods (GET, POST, PUT, DELETE) and the ‘app’ instance.

app.get('/', (req, res) => {
  res.send('Hello World!');
});

In the above code, we define a route for the root URL (/) using the ‘get’ method of the ‘app’ instance. When a client sends a GET request to the root URL, the route handler function will be executed, and the response will be sent with the message “Hello World!”.

We can start the Express application by listening for incoming HTTP requests on a specific port using the ‘listen’ method of the ‘app’ instance.

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In the above code, we start the Express application on port 3000 and log a message to the console when the server is started.

Request & Response

Request: A request is a message sent by a client to a server, requesting a specific action to be performed. In the context of web applications, an HTTP request is commonly used. An HTTP request consists of several components:

1. HTTP Method: It specifies the type of action to be performed on the server. The most commonly used methods are:

2. URL (Uniform Resource Locator): It identifies the location of the resource on the server that the client wants to interact with. For example, https://example.com/api/users.

3. Headers: Headers contain additional information about the request, such as the client’s user agent, content type, or authorization credentials.

4. Body (optional): In some cases, a request may include a body that contains data to be sent to the server. This is commonly used in POST or PUT requests to send data for creating or updating a resource.

Once a server receives a request, it processes it and generates a response.

Response: A response is a message sent by a server to a client in response to a request. Like requests, HTTP responses consist of several components:

1. Status Code: It indicates the outcome of the request. Common HTTP status codes include:

2. Headers: Similar to request headers, response headers provide additional information about the response, such as the content type or caching instructions.

3. Body: The response body contains the data returned by the server. This can be HTML, JSON, XML, or any other format based on the request and the server’s functionality.

The client receives the response and processes it accordingly. For example, in a web browser, the response may be used to render a web page or update the client’s user interface.

Basic Routing

Basic routing is a key feature of web frameworks like Express, where you can define routes to handle different HTTP methods and URLs. Let’s explore how routing works in Express and provide some example code.

In Express, you can define routes using the ‘app’ object, which represents your Express application. Here’s an example of defining a basic route:

const express = require('express');
const app = express();
 
// Define a route for the root URL
app.get('/', (req, res) => {
  res.send('Hello World!');
});
 
// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In the above code, we import the Express module and create an Express application instance using ‘express()’. Then, we define a route for the root URL (‘/’) using the ‘get’ method of the ‘app’ object. When a client sends a GET request to the root URL, the route handler function is executed, and the response is sent with the message “Hello World!”.

You can define routes for other HTTP methods like ‘POST’, ‘PUT’, or ‘DELETE’ in a similar way:

// Define a route for handling a POST request
app.post('/users', (req, res) => {
  // Handle the request and send a response
  res.send('User created successfully!');
});
 
// Define a route for handling a PUT request
app.put('/users/:id', (req, res) => {
  const userId = req.params.id;
  // Handle the request and send a response
  res.send(`User ${userId} updated successfully!`);
});
 
// Define a route for handling a DELETE request
app.delete('/users/:id', (req, res) => {
  const userId = req.params.id;
  // Handle the request and send a response
  res.send(`User ${userId} deleted successfully!`);
});

In the above code, we define routes for creating, updating, and deleting users. The :id in the URL represents a route parameter, allowing you to access dynamic values from the URL using ‘req.params’.
You can also define routes with multiple callback functions or middleware for more complex scenarios:

app.get('/users/:id', (req, res, next) => {
  // Middleware function 1
  // Perform some operations on the request
  console.log('Middleware 1');
 
  // Call the next middleware or route handler
  next();
}, (req, res) => {
  // Middleware function 2
  // Handle the request and send a response
  const userId = req.params.id;
  res.send(`User ${userId} retrieved successfully!`);
});

In this example, we define a route with two middleware functions. The first middleware function performs some operations on the request (e.g., logging), and then calls the next function to pass the control to the next middleware or route handler. Finally, the second middleware function handles the request and sends a response.

Serving Static Files

Serving static files is a common requirement in web applications, where you need to serve files such as HTML, CSS, JavaScript, images, or other static assets to clients. Express provides a built-in middleware called ‘express.static’ that makes it easy to serve static files. Let’s explore how to serve static files in Express.

First, you need to create a directory in your project where you will store your static files. For example, you can create a folder named “public” in your project’s root directory.

Inside the “public” folder, you can place your static files. For instance, you may have an HTML file called “index.html”, a CSS file called “styles.css”, and an image file called “logo.png”.

To serve these static files, you can use the ‘express.static’ middleware in your Express application. Here’s an example:

const express = require('express');
const app = express();
 
// Serve static files from the "public" directory
app.use(express.static('public'));
 
// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In the above code, we use the ‘app.use’ function to register the ‘express.static’ middleware. We pass the path to the directory containing the static files as an argument. In this case, we specify ‘public’ as the directory name. This means that any files in the “public” directory can be accessed by clients.

Now, if you have an HTML file called “index.html” in the “public” directory, it can be accessed by visiting ‘http://localhost:3000/index.html’ in your browser.

Similarly, if you have a CSS file called “styles.css” in the “public” directory, it can be referenced in your HTML file using a relative path like ‘<link rel=”stylesheet” href=”/styles.css”>’.

The ‘express.static’ middleware takes care of mapping URLs to the corresponding files in the specified directory. It automatically serves the appropriate file to the client based on the requested URL.

GET And POST Methods

GET Method: The GET method is one of the most commonly used HTTP methods. It is used to retrieve data from a server by sending a request. When a client sends a GET request, it specifies the resource it wants to retrieve from the server. This method is considered “safe” as it should not have any side effects on the server.

Example code for handling a GET request in Express:
const express = require('express');
const app = express();
 
// Define a route for handling a GET request
app.get('/users', (req, res) => {
  // Retrieve user data from a database or another source
  const users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
  ];
 
  // Send the users as a response
  res.json(users);
});
 
// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In the above code, we define a route using the ‘app.get’ method to handle a GET request to the ‘/users’ URL. When the client sends a GET request to this route, the route handler function is executed, and the server responds by sending an array of user data in JSON format.

POST Method: The POST method is used to submit data to the server to create or update a resource. When a client sends a POST request, it includes data in the request body that will be processed by the server. This method can have side effects on the server, such as creating a new record in a database.

Example code for handling a POST request in Express:
const express = require('express');
const app = express();
 
// Parse JSON data in the request body
app.use(express.json());
 
// Define a route for handling a POST request
app.post('/users', (req, res) => {
  const { name, email } = req.body;
 
  // Process the data and create a new user
  // Save the user to a database or perform other operations
 
  // Send a success message as a response
  res.send('User created successfully!');
});
 
// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In the above code, we use the ‘app.post’ method to define a route for handling a POST request to the ‘/users’ URL. We also use the ‘express.json’ middleware to parse the JSON data in the request body. When the client sends a POST request to this route, the route handler function is executed. It accesses the data from the request body and performs the necessary operations, such as creating a new user in a database. Finally, the server responds with a success message.

By using the GET and POST methods in Express, you can handle different types of client requests and perform appropriate actions on the server, such as retrieving data or creating new resources.

Cookies Management

Cookies are a widely used mechanism for managing state and maintaining user session information in web applications. In Express, you can easily handle cookies using the ‘cookie-parser’ middleware and the ‘res.cookie’ method. Let’s explain cookies management and provide an example code snippet.
First, you need to install the ‘cookie-parser’ package by running the following command:

npm install cookie-parser

Once you have installed ‘cookie-parser’, you can use it in your Express application as middleware. Here’s an example:

const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
 
// Use the cookieParser middleware
app.use(cookieParser());
 
// Define a route for setting a cookie
app.get('/set-cookie', (req, res) => {
  // Set a cookie with a name and value
  res.cookie('username', 'John');
 
  // Send a response
  res.send('Cookie set successfully!');
});
 
// Define a route for retrieving the cookie
app.get('/get-cookie', (req, res) => {
  // Retrieve the value of the cookie
  const username = req.cookies.username;
 
  // Send the value as a response
  res.send(`Username: ${username}`);
});
 
// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In the above code, we first import the cookie-parser middleware and use it with ‘app.use’ to enable cookie parsing for incoming requests.

Next, we define a route for setting a cookie using the ‘res.cookie’ method. Inside the route handler, we call ‘res.cookie’ with the name and value of the cookie we want to set. In this example, we set a cookie named ‘username’ with the value ‘John’.

To retrieve the value of the cookie, we define another route for retrieving the cookie. In the route handler, we access the value of the ‘username’ cookie using ‘req.cookies’.username and send it as a response.
When a client visits the ‘/set-cookie’ route, the server sets the ‘username’ cookie with the value ‘John’. The client’s browser stores this cookie. Then, when the client visits the ‘/get-cookie’ route, the server retrieves the value of the ‘username’ cookie and sends it back as a response.

This is a basic example of how to manage cookies in Express. You can set additional options for cookies, such as expiration time, domain, and secure flag, by passing an options object as the third argument to res.cookie.

Conclusion

Express is a powerful and flexible web application framework for Node.js that provides a wide range of features and capabilities for building high-performance web applications. With its simple API, middleware, routing, template engines, and error-handling mechanisms, developers can quickly and easily create scalable and maintainable web applications with Express.

Exit mobile version