Request/Response
Express adds friendly helpers to the request and response objects.
In this page:
Syntax
req.params.name
req.query.name
req.body
res.json(data);
Request/Response
On the request you have req.params, req.query, req.body (after a parser) and req.get for headers. On the response use res.send, res.json, res.status, res.redirect and res.sendFile. Chaining like res.status(404).json(...) is common.
Note:
res.json sets the Content-Type header for you.
Example: Request/Response
app.get("/search", (req, res) => {
const { q = "", page = "1" } = req.query;
if (!q) return res.status(400).json({ error: "q is required" });
res.json({ q, page: Number(page), agent: req.get("user-agent") });
});
app.get("/old", (req, res) => res.redirect(301, "/search?q=new"));
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Sending a response twice
- Forgetting body parser middleware
- Not setting the status
Chapter Summary
- req.params, query and body carry input
- res.json and res.send respond
- res.status sets the code
- Chain helpers
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: