Loading

Quipoin Menu

Learn • Practice • Grow

node-js / Request & Response Objects
interview

Q1. What are the main properties of the request object in Node.js?
Important req properties: req.method (HTTP method), req.url (request URL), req.headers (headers object), req.httpVersion (HTTP version), req.socket (underlying socket), req.statusCode (for client requests). For incoming requests, you can also read the body via data events.

Q2. How do you read the request body?
The request object is a readable stream. Collect data chunks:
let body = []; req.on('data', chunk => { body.push(chunk); }).on('end', () => { body = Buffer.concat(body).toString(); // process body });
. For JSON, parse with JSON.parse(body). This is how body parsing works under the hood.

Q3. What methods does the response object provide?
The response object (http.ServerResponse) is a writable stream. Key methods: res.writeHead(statusCode, headers) - set status and headers, res.setHeader(name, value) - set individual header, res.write(chunk) - write data, res.end([data]) - end response (optionally send final data), res.getHeader(name) - get header value.

Q4. How do you send JSON responses?
Set Content-Type header to 'application/json', then stringify and send:
res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ message: 'Success', data: [1,2,3] }));
. For large JSON, consider streaming. Many frameworks like Express do this automatically.

Q5. How do you handle response errors?
Listen for error events on the response:
res.on('error', (err) => { console.error('Response error:', err); });
Also ensure you handle errors in your request handler. If headers are already sent, res.end() may throw - use try/catch. Always end responses to prevent hanging connections.