- Express.js Basics
- Express.js HOME
- Express.js Introduction
- Express.js Installation
- Express.js Basic App
- Express.js Routing
- Basics Routing
- Route Parameters
- Handling Query Strings
- Router Middleware
- Middleware
- What is Middleware?
- Application-Level Middleware
- Router-Level Middleware
- Built-In Middleware
- Error-Handling Middleware
- Third-Party Middleware
- Express.js HTTP
- Handling GET Requests
- Handling POST Requests
- Handling PUT Requests
- Handling DELETE Requests
- Templating Engines
- Using Templating Engines
- Setting Up EJS
- Setting Up Handlebars
- Setting Up Pug
- Request/Response
- Request Object
- Response Object
- Handling JSON Data
- Handling Form Data
- Static Files
- Serving Static Files
- Setting Up Static Folders
- Managing Assets
- Express.js Advanced
- Middleware Stack
- CORS in Express.js
- JWT Authentication
- Session Handling
- File Uploads
- Error Handling
- Databases
- Express.js with MongoDB
- MongoDB CRUD Operations
- Express.js with MySQL
- MySQL CRUD Operations
- Deployment
- Deploying Express.js Apps to Heroku
- Deploying Express.js Apps to AWS
- Deploying Express.js Apps to Vercel
Express.js Handling GET Requests
In the world of web development, GET requests are the backbone of how we consume information. Every time you type a URL into your browser and hit enter, you are performing a GET request. In the context of an Express.js application, handling these requests means defining "routes" that listen for a specific URL and respond with the data the user asked for—whether that is an HTML page, a JSON object for a mobile app, or a simple string of text.
Key Features of Handling GET Requests
- Resource Retrieval: The primary purpose of a GET request is to "read" or fetch data from your server.
- Path Parameters: These allow you to create dynamic routes, such as
/users/42, where "42" is a variable you can capture. - Query Strings: These are used for filtering or sorting data, appearing at the end of a URL like
/products?sort=price. - Safety: Because GET requests shouldn't change data on the server, they are safe to be cached by browsers and bookmarked by users.
Handling Basic GET Requests
To handle a GET request in Express, you use the app.get() method. This method requires two main arguments: the path (the URL) and a callback function. This function provides two vital objects: req (the Request coming in) and res (the Response you will send back).
Example:
const express = require('express');
const app = express();
// Handle GET request to the root path ("/")
app.get('/', (req, res) => {
// res.send tells Express to finish the request and send this string back
res.send('Hello, World! Welcome to our Express Server.');
});
// Start the server on port 3000
app.listen(3000, () => {
console.log('Server is live at http://localhost:3000');
});
res.send(), res.json(), or res.end(), the browser will keep spinning until it eventually times out because the server never "closed" the conversation.
Handling GET Requests with Path Parameters
Static routes are great, but real-world apps need to handle dynamic data. Path parameters allow you to capture values from the URL by using a colon (:) prefix in the route definition. This is how you identify specific resources, like a single user in a database.
Example:
app.get('/user/:id', (req, res) => {
// Express automatically populates req.params with your dynamic values
const userId = req.params.id;
res.send(`You are viewing the profile for User ID: ${userId}`);
});
If a user visits /user/99, Express sets req.params.id to "99". This makes it incredibly easy to look up that specific user in your database.
app.get('/user/settings') after app.get('/user/:id'), Express will treat "settings" as the ID. Always place your specific static routes above your dynamic parameterized routes.
Handling GET Requests with Query Strings
Query strings are key-value pairs that appear after a ? in the URL. They are perfect for optional parameters like search terms, pagination, or filters. Unlike path parameters, you don't need to define them in your route path; Express parses them automatically into the req.query object.
Example:
app.get('/search', (req, res) => {
// If the URL is /search?term=javascript&limit=10
const searchTerm = req.query.term;
const limit = req.query.limit;
res.send(`Searching for "${searchTerm}" with a limit of ${limit} results.`);
});
A request to /search?term=nodejs will allow you to access "nodejs" via req.query.term.
Example of Handling GET Requests with Both Parameters and Query Strings
In complex applications, you often combine both methods. For example, you might want to view a specific category of products (path parameter) and then sort them (query string).
app.get('/category/:name', (req, res) => {
const categoryName = req.params.name;
const sortBy = req.query.sort || 'name'; // Default to 'name' if no sort is provided
res.send(`Displaying products in ${categoryName}, sorted by ${sortBy}.`);
});
For a request to /category/shoes?sort=price, the server extracts "shoes" from the path and "price" from the query string to deliver a tailored response.
Handling GET Requests with a Callback Function
While res.send() is great for text and HTML, most modern web developers use Express to build APIs. In these cases, you should use res.json(). This method automatically sets the correct headers so the client knows it is receiving data, not just a string.
Example:
app.get('/api/status', (req, res) => {
// res.json converts your JavaScript object into a JSON string automatically
res.json({
status: 'Online',
uptime: '24 hours',
version: '1.0.2'
});
});
res.json(). It ensures that the Content-Type header is set to application/json, which helps frontend frameworks like React or Vue parse the data correctly.
Example of Handling Multiple GET Requests
Organizing your application involves creating multiple routes to handle different "pages" or data points. Express matches the requested URL against your defined routes from top to bottom.
Example:
app.get('/', (req, res) => {
res.send('Welcome to the Home Page!');
});
app.get('/about', (req, res) => {
res.send('This is the About Page. We are developers.');
});
app.get('/contact', (req, res) => {
res.send('Contact us at [email protected]');
});
Each path leads to a unique "handler," allowing your application to scale to hundreds of different URLs.
Summary
Handling GET requests is one of the most fundamental skills for any Express.js developer. By mastering the app.get() method, you gain the ability to serve content, build dynamic experiences using path parameters, and offer advanced filtering through query strings. Whether you are returning a simple "Hello World" or building a complex JSON API, these patterns form the foundation of how your application interacts with the rest of the web.