GET route handling lets your server respond when someone asks for information. It helps deliver web pages or data when users visit a link.
0
0
GET route handling in Express
Introduction
When you want to show a homepage or a webpage to visitors.
When you need to send data like a list of products to a user.
When a user clicks a link and your server should send back the right content.
When you want to test if your server is running by visiting a simple URL.
When you want to fetch user details by their ID from the URL.
Syntax
Express
app.get('/path', (req, res) => { // code to handle the request res.send('response') })
app.get listens for GET requests on the given path.
The callback has req for request info and res to send back a response.
Examples
Sends a welcome message when someone visits the root URL.
Express
app.get('/', (req, res) => { res.send('Welcome to the homepage!') })
Responds with a simple About page text.
Express
app.get('/about', (req, res) => { res.send('About us page') })
Reads a user ID from the URL and sends it back in the response.
Express
app.get('/user/:id', (req, res) => { const userId = req.params.id res.send(`User ID requested: ${userId}`) })
Sample Program
This program creates a simple Express server with two GET routes. The root route sends a greeting message. The second route reads a name from the URL and sends a personalized greeting.
Express
import express from 'express' const app = express() const port = 3000 app.get('/', (req, res) => { res.send('Hello! This is the homepage.') }) app.get('/greet/:name', (req, res) => { const name = req.params.name res.send(`Hello, ${name}! Welcome to our site.`) }) app.listen(port, () => { console.log(`Server running at http://localhost:${port}`) })
OutputSuccess
Important Notes
GET routes only respond to GET requests, which are usually for getting data or pages.
Use req.params to get dynamic parts of the URL like IDs or names.
Always send a response with res.send(), res.json(), or similar to avoid hanging requests.
Summary
GET route handling lets your server answer requests for pages or data.
Use app.get(path, callback) to define what happens when a URL is visited.
You can read URL parts with req.params to customize responses.