Node.js
Request and response
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.
Exercise 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: ".
Show example 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(); });
});
});
Test yourself
-
Match each property to its meaning
- req.method
- Request method
- req.url
- Request path
- res.end
- Finishes the response
- res.setHeader
- Adds a header
-
What does req.url hold?
http.createServer((req, res) => { ... })
- The response content
- The request path (e.g. /bilgi)
- The server's port number
- The request headers
Show answer
The request path (e.g. /bilgi) — req.url holds the request path.
-
Complete the res.end call
const server = http.createServer((req, res) => { res.____("Merhaba"); });
Show answer
const server = http.createServer((req, res) => { res.end("Merhaba"); });
Next lesson: Routing