Lesson 22 of 30
Request and Response
73% complete
Chapters
Chapter 22
Request and Response
Learn how Express handles HTTP requests and sends responses.
Theory
In Express route handlers, req represents the incoming request and res represents the outgoing response.
The request can contain:
• Parameters
• Query strings
• Headers
• Body data
The response can contain:
• JSON
• Text
• HTML
• Status codes
Express provides methods such as res.send(), res.json(), and res.status().
Example
Node.js Example
app.get("/user/:id", (req, res) => {
const id = req.params.id;
res.status(200).json({
userId: id
});
});Output
The API returns the requested user ID as JSON.
Practice
Create an endpoint that receives a route parameter and returns it in JSON format.
Interview Questions
1.
What are req and res in Express?
2.
What is req.params?
3.
What does res.json() do?
Quick Quiz
Which option best matches this chapter?
A.Request and response objects
B.Database and cache objects
C.HTML and CSS objects
D.Server and browser processes
Answer: Request and response objects