Handling HTTP GET Requests
Handling an HTTP GET request in Express means defining a route that listens for GET requests on a path and sends back a response, usually JSON. GET is the method browsers and API clients use to read data, such as a list of courses or one course by its id, without changing anything on the server.
Defining GET routes with app.get
app.get(path, handler) registers a handler for one path. The handler receives the request object req, which holds everything the client sent, and the response object res, which you use to reply.
const express = require('express');
const app = express();
const courses = [
{ id: 1, title: 'HTML Basics', level: 'beginner' },
{ id: 2, title: 'Node.js APIs', level: 'intermediate' },
{ id: 3, title: 'CSS Layouts', level: 'beginner' },
];
// all courses, optionally filtered: /api/courses?level=beginner
app.get('/api/courses', (req, res) => {
const { level } = req.query;
const result = level ? courses.filter((c) => c.level === level) : courses;
res.json(result);
});
// one course by id: /api/courses/2
app.get('/api/courses/:id', (req, res) => {
const id = Number(req.params.id);
const course = courses.find((c) => c.id === id);
if (!course) {
return res.status(404).json({ message: 'Course not found' });
}
res.json(course);
});
app.listen(3000, () => console.log('API on http://localhost:3000'));
Reading what the client asked for
req.paramsholds route parameters, the named parts of the path like:id. They identify which resource is wanted.req.queryholds the query string after the?, such aslevel=beginner. It is used for optional extras like filtering, sorting and pagination.req.headersgives access to headers such asauthorization.
Both params and query values always arrive as strings. That is why the example converts the id with Number() before comparing.
Sending the response
res.json() converts an object or array to JSON and sets the Content-Type header for you. res.send() handles strings and buffers. res.status(code) sets the status and can be chained, as in res.status(404).json(...). A handler must send exactly one response; if it sends none, the client waits until it times out.
The string-versus-number bug
The most common mistake in GET handlers is comparing a parameter directly with numeric ids: courses.find((c) => c.id === req.params.id). Since "2" === 2 is false, every lookup fails and every request returns 404, even for ids that exist. Convert first, and consider rejecting non-numeric ids with a 400 response.
A second error is forgetting return before sending the 404. The code then continues to res.json(course) and Express throws "Cannot set headers after they are sent to the client".
Route order matters
Express checks routes in the order they are defined and uses the first match. If you define /api/courses/:id before a route like /api/courses/popular, the word "popular" is captured as an id. Put fixed paths before parameter paths.
When the data comes from a database
Real APIs rarely keep data in an array. Handlers usually become async functions that await a database query. Wrap that query in try and catch, and send a 500 response with a short message if it fails. In Express 4, an error thrown inside an async handler is not caught for you, so without that block the request can hang or the process can log an unhandled rejection.
Keep GET handlers free of side effects. They should not create, update or delete records, because browsers, crawlers and caches may repeat GET requests freely.
Checking your routes
GET requests are easy to test: open the URL in a browser, or run curl http://localhost:3000/api/courses?level=beginner. Tools like Postman become more useful for POST requests, which carry a body, and that is the next step.
Main idea: app.get plus req.params for identity, req.query for options, convert strings before comparing, and return a clear 404 when nothing matches.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.