#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Node.js & Express

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.params holds route parameters, the named parts of the path like :id. They identify which resource is wanted.
  • req.query holds the query string after the ?, such as level=beginner. It is used for optional extras like filtering, sorting and pagination.
  • req.headers gives access to headers such as authorization.

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.

Explore Course