Chapter 6: Creating a Basic Server
Chapter 6 of 15
Chapter 6: Creating a Basic Server
6.1 HTTP Server
Node.js http module allows you to create HTTP servers. This is the foundation of web applications.
const http = require('http');
// Create HTTP server
const server = http.createServer((req, res) => {
// Set response headers
res.writeHead(200, {
'Content-Type': 'text/plain',
'X-Custom-Header': 'MyValue'
});
// Send response
res.end('Hello World');
});
// Start server
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Request Object (req):
- req.method: HTTP method (GET, POST, etc.)
- req.url: Request URL path
- req.headers: Request headers
- req.on('data'): Receive request body data
Response Object (res):
- res.writeHead(): Set status code and headers
- res.write(): Write response data
- res.end(): End response
- res.statusCode: Set status code
6.2 Handling Different Routes
Route requests to different handlers based on URL and method.
const http = require('http');
const server = http.createServer((req, res) => {
const { method, url } = req;
if (method === 'GET' && url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Home Page</h1>');
} else if (method === 'GET' && url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>About Page</h1>');
} else if (method === 'GET' && url === '/api/users') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify([{ id: 1, name: 'John' }]));
} else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found</h1>');
}
});
server.listen(3000);
6.3 Handling POST Requests
Process POST requests and read request body data.
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/api/users') {
let body = ';
// Collect request data
req.on('data', chunk => {
body += chunk.toString();
});
// Process when data is complete
req.on('end', () => {
try {
const data = JSON.parse(body);
// Process data (save to database, etc.)
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true, data }));
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000);
6.4 Server Best Practices
Follow best practices when creating servers.
- Handle errors gracefully
- Set appropriate status codes
- Set correct Content-Type headers
- Validate request data
- Implement proper error handling
- Use environment variables for port
- Log requests for debugging