Request & Response Objects
Every time a client makes a request to your server, Node.js creates two objects: the **request object** (`req`) and the **response object** (`res`). These objects are your main tools for understanding what the client wants and for sending back a response. Let's explore them in detail.
The Request Object (req)
The request object contains all information about the incoming request: the URL, HTTP method, headers, query parameters, and more.
| Property/Method | Description |
|---|---|
| `req.url` | The URL path (e.g., `/about?name=john` includes query string). |
| `req.method` | HTTP method (GET, POST, PUT, DELETE, etc.). |
| `req.headers` | An object containing all HTTP headers. |
| `req.httpVersion` | HTTP version used by the client. |
| `req.socket` | Information about the connection (remote address, port). |
Think of the request object as the "order form" a customer fills out. It tells you what they want (URL), how they want it (method), and any special instructions (headers).
Request Object Examples
const http = require('http');
const server = http.createServer((req, res) => { console.log('URL:', req.url); console.log('Method:', req.method); console.log('Headers:', req.headers); console.log('User-Agent:', req.headers['user-agent']); res.end('Check your console!');});
server.listen(3000);Parsing the URL
Often you need to separate the path from query parameters. Node.js provides the `url` module for this.
const url = require('url');
const server = http.createServer((req, res) => { const parsedUrl = url.parse(req.url, true); <!-- true parses query string --> console.log('Path:', parsedUrl.pathname); console.log('Query:', parsedUrl.query); res.end('OK');});The Response Object (res)
The response object is used to send data back to the client. You set status codes, headers, and the response body using its methods.
| Method | Description |
|---|---|
| `res.writeHead(statusCode, headers)` | Sets the HTTP status code and headers. |
| `res.setHeader(name, value)` | Sets a single header. |
| `res.write(chunk)` | Sends a chunk of the response body (can be called multiple times). |
| `res.end([data])` | Signals that the response is complete. Optionally sends final data. |
| `res.statusCode` | Property to set status code (alternative to writeHead). |
Response Examples
<!-- Method 1: Using writeHead -->res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ message: 'Hello' }));
<!-- Method 2: Setting properties individually -->res.statusCode = 200;res.setHeader('Content-Type', 'text/html');res.write('');
res.write('Hello World');res.write('');res.end();Common HTTP Status Codes
| Code | Meaning |
|---|---|
| 200 | OK – Success |
| 201 | Created – Resource created successfully |
| 301 | Moved Permanently – Redirect |
| 400 | Bad Request – Client error |
| 404 | Not Found |
| 500 | Internal Server Error |
Two Minute Drill
- `req` gives you request details: url, method, headers.
- `res` lets you build and send the response.
- Use `url.parse()` to split path and query string.
- Set status codes appropriately (200, 404, 500, etc.).
- Always call `res.end()` to finish the response.
- Headers are case-insensitive but commonly written in lowercase.
Need more clarification?
Drop us an email at career@quipoinfotech.com
