Request and response
- Node.js course
- Intermediate
- Lesson 14/116
- 5 min
Learn the request and response objects.
Request and response
The handler's two parameters are req and res. req carries request details: req.method (GET, POST...), req.url (request path) and req.headers (headers).
res provides methods to write the response. res.setHeader("Content-Type", "text/plain") adds a header. res.write("chunk") writes the response in pieces, and res.end() finishes it. The most common usage is res.end("full response"), which both writes the content and closes the connection. res.end must be called exactly once per request; otherwise the request hangs.
Reading request details
To read a request's method and path you use req.method and req.url. Example: console.log(req.method + " " + req.url); prints GET / for a GET / request.
With this info you can give different responses to different paths; this is the basis of routing. req.headers is an object; you access headers like req.headers["host"]. To customize the response, setting the content type with res.setHeader is a good habit: res.setHeader("Content-Type", "text/plain"). This tells the browser how to interpret the response.
Practice Listen to a request and respond
Import the http module. Create a server with createServer: the handler does console.log("Request: " + req.method) and responds with res.end("OK"). The ready-made code below starts the server, sends a request and prints "Reply: ".
Starter code
// Import the http module and create a server
// write here
server.listen(3000, () => {
http.get("http://localhost:3000/", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});Sample solution
const http = require("http");
const server = http.createServer((req, res) => {
console.log("Request: " + req.method);
res.end("OK");
});
server.listen(3000, () => {
http.get("http://localhost:3000/", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});Expected output
İstek: GET Yanıt: Tamam
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each property to its meaning
| Term | Meaning |
|---|---|
req.method |
Request method |
req.url |
Request path |
res.end |
Finishes the response |
res.setHeader |
Adds a header |
2 What does req.url hold?
http.createServer((req, res) => { ... })- The response content
- The request path (e.g. /bilgi) Correct answer
- The server's port number
- The request headers
Explanation: req.url holds the request path.
3 Complete the res.end call
const server = http.createServer((req, res) => { res.____("Merhaba"); });
const server = http.createServer((req, res) => { res.end("Merhaba"); });
Explanation: res.end sends and finishes the response.