Open In App

Express app.get() Request Function

Last Updated : 25 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The app.get() function is used to define routes on your server that handle HTTP GET requests. A GET request is typically used when the client asks the server to send back some information, like retrieving a webpage or data from a database.

It’s an essential part of building websites and APIs, as it allows developers to specify what happens when a client requests data, whether it’s showing a webpage, fetching information, or pulling data from a database.

Syntax

app.get( path, callback )

In this syntax:

  • path: It defines the route for which the middleware function is triggered.
  • callback: It can be one or more functions that process the request that has been made to the server.

How does app.get() work in Express?

Below are the basic steps to understand how app.get() works.

1. Import Express and Create an App

This code imports the Express module and creates an Express application instance. This app instance is used to define routes and handle HTTP requests.

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

2. Define a GET Route

This code defines a route that listens for GET requests at /hello. When accessed, it responds with “Hello, World!”.

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

3. Start the Server

This code starts the server and makes it listen on port 3000. When the server runs, it logs “Server is running on port 3000” to the console.

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

Steps to create the application

To use Express in your project, follow these steps:

Step 1: Install ExpressJs

To begin, you need to install Express. You can do this by running the following command in your terminal:

npm install express

Step 2: Verify Installation

Once Express is installed, you can check the version to make sure it’s set up correctly. Run this command in your terminal to confirm the installation:

npm version express

Project Structure

NodeProj

The package.json will show Express in the dependencies:

"dependencies": {
    "express": "^5.1.0",
}

Example using app.get()

Here is a simple example to demonstrate app.get() in action:

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

// Define a GET route
app.get('/', (req, res) => {
    res.send('<h1>Welcome to Express.js!</h1>');
});

app.listen(PORT, () => {
    console.log(`Server listening on PORT ${PORT}`);
});

Output:

Simple use of Express.get()

Example using app.get()

In this example:

  • Importing Express: It imports the Express.js framework using require(‘express’), allowing us to create a web server.
  • Creating an Express App: The app variable is initialized with express(), which creates an instance of an Express application.
  • Defining a Route: A GET request handler is defined for the root (‘/’) route, responding with an HTML message: “Welcome to Express.js!”.
  • Starting the Server: The server listens on port 3000, and when started, logs a message indicating it’s running.

Using Middleware with app.get()

Express allows you to add middleware to routes, which are functions that execute before the final response. Here’s an example of using middleware with app.get():

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

// Define a GET route
app.get('/', (req, res) => {
    res.send('<h1>Welcome to Express.js!</h1>');
});

app.listen(PORT, () => {
    console.log(`Server listening on PORT ${PORT}`);
});
app.get('/middleware', (req, res, next) => {
    console.log('Middleware executed');
    next();
}, (req, res) => {
    res.send('<h1>Response after middleware</h1>');
});
Screenshot-2025-03-04-130848

Example of middleware with app.get()

In this example:

  • Importing and Initializing Express: The code imports Express.js and creates an instance of the Express application (app). The server is set to listen on port 3000.
  • Defining a Basic Route: A GET request handler for ‘/’ sends a simple HTML response: “<h1>Welcome to Express.js!</h1>”.
  • Using Middleware in a Route: The ‘/middleware’ route includes a middleware function that logs “Middleware executed” to the console before passing control to the next function using next().
  • Handling the Final Response: After the middleware function runs, the next function sends the response: “<h1>Response after middleware</h1>”, completing the request-response cycle.

Use cases of app.get()

Here are some practical use cases of app.get():

  • Serving Web Pages: app.get() can be used to deliver static or dynamic web pages when users visit specific URLs.
  • Retrieving Data: It helps fetch and send data from the server to clients, such as user details, product information, or articles.
  • Handling URL Parameters: The function can process dynamic URL parameters to customize responses based on user input.
  • Processing Query Strings: It allows handling query parameters in the request URL to filter or customize the data sent back to the client.
  • API Endpoint Creation: app.get() is commonly used to define API routes that return JSON data, making it essential for building RESTful web services.

Advantages of using app.get()

Using app.get() offers several benefits for handling HTTP GET requests:

  • It simplifies defining routes for retrieving data from the server.
  • The code remains clean and easy to read, making route handling straightforward.
  • Middleware can be added before the response, enabling tasks like logging, authentication, or data processing.
  • It keeps the application modular, making it easier to manage as it grows.

Performance Optimization with app.get()

When building an Express app, optimizing performance ensures that the application runs smoothly and quickly. Here are a few simple techniques to enhance performance when using app.get()

  • Caching Responses: Caching involves saving a copy of frequently requested data so it doesn’t need to be retrieved every time a request is made. This helps improve the app’s speed by reducing repetitive data fetching.
  • Compression: Compression makes the data smaller, which helps it travel faster from the server to the client, especially when dealing with large files. By turning on compression, less data needs to be sent, making the transfer quicker.
  • Asynchronous Code: Asynchronous code helps the server stay active while it waits for tasks like database queries or API calls to finish. This way, the server can keep working on other requests without getting stuck waiting for one task to complete

Conclusion

The get() function is used in many ways, with or without middleware. It helps you set up routes, send dynamic content, and create APIs. You can use it to handle requests, like when you need to show a webpage or get data. Mastering this function makes it easier to get data, improve app speed, and keep your web applications organized.



Next Article

Similar Reads