Express.js — HTTP Server Creation & Response Methods
Welcome to Express.js — HTTP Server Creation & Response Methods in our Express.js Complete Masterclass! Create your first Express server, handle HTTP GET requests, and send JSON responses.
The `express()` function instantiates an Express application object (`app`). Calling `app.listen(port, callback)` binds the server to an HTTP port. Every incoming request delivers `req` (Request Object) and `res` (Response Object) to route handlers.
- Master the underlying Node.js event loop mechanics for HTTP Server Creation & Response Methods.
- Implement non-blocking, asynchronous execution pipelines in compliance with production API standards.
- Enforce strict OWASP Top 10 API security guidelines and performance optimizations.
| Response Method | Output Content-Type | Primary Use Case |
|---|---|---|
| `res.send(body)` | Auto-detected (text/html, buffer) | Sending strings, HTML content, or buffers |
| `res.json(obj)` | `application/json` | Serializing JavaScript objects into JSON API responses |
| `res.sendStatus(code)` | `text/plain` | Sending status text corresponding to HTTP status code |
| `res.end()` | None | Ending response cycle without body content (e.g. 204) |
import express from 'express';
const app = express();
// Text response
app.get('/text', (req, res) => {
res.send('Hello World from Express!');
});
// JSON API response
app.get('/api/data', (req, res) => {
res.json({ success: true, count: 2, items: ['Node', 'Express'] });
});
// HTTP 204 No Content
app.get('/empty', (req, res) => {
res.status(204).end();
});
app.listen(3000);
// Standardized JSON Response Pattern
import express from 'express';
const app = express();
const sendSuccess = (res, data, status = 200) => {
res.status(status).json({
success: true,
timestamp: new Date().toISOString(),
data
});
};
app.get('/api/v1/users', (req, res) => {
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
sendSuccess(res, users);
});
app.listen(3000);
- Calling `res.json()` or `res.send()` multiple times within a single request path causing "Cannot set headers after they are sent to the client" errors.
- Forgetting to call `res.end()` or `res.json()` resulting in hanging HTTP requests until browser timeout.
❓ Question: What happens if I don't call res.send() or res.json()?
Answer: The HTTP client will wait indefinitely until connection timeout occurs because Express does not close the HTTP socket automatically without a response invocation.
❓ Question: Difference between res.send() and res.json()?
Answer: `res.json()` explicitly sets `Content-Type: application/json` and formats JavaScript objects via `JSON.stringify()`. `res.send()` handles strings, HTML buffers, and objects dynamically.
Build a server with routes `/html` (returns HTML `