Suggest an editImprove this articleRefine the answer for “How do you handle a request inside createServer()?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)The `(req, res)` callback passed to `http.createServer()` is the handler for every incoming request: `req` (`IncomingMessage`) holds the method, URL, headers, and body as a Readable Stream, while `res` (`ServerResponse`) is a Writable Stream you write the status, headers, and response data into. **Key point:** Node doesn't parse JSON or routes for you - you inspect `req.method`/`req.url` yourself, collect the body via the `data`/`end` events yourself, and build the response via `res.writeHead()`/`res.end()` yourself.Shown above the full answer for quick recall.Answer (EN)ImageWhen you call: ```javascript import http from 'node:http'; const server = http.createServer((req, res) => { // Handle the request here }); server.listen(3000); ``` the `(req, res)` function is the **handler for every incoming request**. Inside it, you decide **what to do with this request and what response to send back**. ## 1. What `req` and `res` are - `req` (`IncomingMessage`) is the request object, everything that came from the client: - `req.method`, the method (GET, POST, PUT, DELETE, etc.) - `req.url`, the path and query parameters - `req.headers`, the headers - `req` itself is a **Readable Stream** you can read the request body from - `res` (`ServerResponse`) is the response object you send back to the client: - `res.statusCode`, the response code (200 by default) - `res.setHeader(name, value)`, sets headers - `res.write(data)`, writes data into the stream - `res.end([data])`, ends the response (you can pass the final data) ## 2. Example: basic GET request handling ```javascript import http from 'node:http'; const server = http.createServer((req, res) => { if (req.method === 'GET' && req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('Home page'); } else if (req.method === 'GET' && req.url === '/about') { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('About us'); } else { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('Page not found'); } }); server.listen(3000); ``` Here the handler inspects `req.method` and `req.url` and returns different responses. ## 3. Example: handling a POST request (reading the body) The request body doesn't arrive all at once, it arrives **in chunks**, so `req` works as a stream (`Readable Stream`): ```javascript const server = http.createServer((req, res) => { if (req.method === 'POST' && req.url === '/echo') { let body = ''; req.on('data', chunk => (body += chunk)); req.on('end', () => { const data = JSON.parse(body); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ youSent: data })); }); } else { res.writeHead(404); res.end(); } }); ``` Node doesn't parse JSON on its own, you read the data stream, collect it into a string, and parse it yourself. ## 4. Adding headers and statuses ```javascript res.statusCode = 201; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ message: 'Created' })); ``` or in one line: ```javascript res.writeHead(201, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Created' })); ``` ## 5. Returning HTML, JSON, or files - **HTML** ```javascript res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end('<h1>Hello</h1>'); ``` - **JSON** ```javascript res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ok: true })); ``` - **A file (streamed)** ```javascript import { createReadStream } from 'node:fs'; import { pipeline } from 'node:stream'; if (req.url === '/file') { res.writeHead(200, { 'Content-Type': 'text/plain' }); pipeline(createReadStream('file.txt'), res, err => { if (err) console.error(err); }); } ``` ## 6. What happens during request handling 1. The client makes an HTTP request (e.g. a browser opens a page). 2. Node accepts the request and calls your `(req, res)` callback. 3. You inspect the path, method, headers, body. 4. You build the response, setting the code, headers, and sending the data. 5. Node automatically closes the connection (or keeps it open, with keep-alive). ## 7. The core idea > With `createServer()` you get **low-level access** to the HTTP request and response. > It's a "clean" entry point, from there, you decide > how to route, what to return, and how to process the data.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.