const http = require('http');
// Create a test server to demonstrate request headers
const server = http.createServer((req, res) => {
// Log request information
console.log(`Request received: ${req.method} ${req.url}`);
console.log(`HTTP Version: ${req.httpVersion}`);
// Display standard headers
console.log('\nStandard Headers:');
const stdHeaders = ['host', 'user-agent', 'accept', 'accept-language', 'content-type', 'content-length'];
stdHeaders.forEach(header => {
if (req.headers[header]) {
console.log(`${header}: ${req.headers[header]}`);
}
});
// Display raw headers (name-value pairs)
console.log('\nRaw Headers:');
for (let i = 0; i < req.rawHeaders.length; i += 2) {
console.log(`${req.rawHeaders[i]}: ${req.rawHeaders[i+1]}`);
}
// Create response
res.writeHead(200, {'Content-Type': 'text/html'});
// Send response with headers information
res.end(`
<!DOCTYPE html>
<html>
<head>
<title>Request Headers</title>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; margin: 20px; }
pre { background: #f4f4f4; padding: 10px; border-radius: 5px; overflow-x: auto; }
.header-table { width: 100%; border-collapse: collapse; margin: 20px 0; }
.header-table th, .header-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
.header-table th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h1>Your Request Headers</h1>
<h2>Processed Headers</h2>
<table class="header-table">
<tr><th>Header</th><th>Value</th></tr>
${Object.entries(req.headers).map(([key, value]) =>
`<tr><td><strong>${key}</strong></td><td>${value}</td></tr>`
).join('')}
</table>
<h2>Raw Headers</h2>
<pre>${JSON.stringify(req.rawHeaders, null, 2)}</pre>
<h2>Request Information</h2>
<ul>
<li><strong>Method:</strong> ${req.method}</li>
<li><strong>URL:</strong> ${req.url}</li>
<li><strong>HTTP Version:</strong> ${req.httpVersion}</li>
<li><strong>Client IP:</strong> ${req.socket.remoteAddress}:${req.socket.remotePort}</li>
</ul>
</body>
</html>
`);
});
// Start server
const PORT = 3006;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
// Make a request to demonstrate headers
console.log('\nMaking a request with custom headers...');
const req = http.request({
hostname: 'localhost',
port: PORT,
path: '/headers-demo',
method: 'GET',
headers: {
'User-Agent': 'Node.js Demo Client',
'X-Custom-Header': 'Custom Value',
'Accept': 'text/html,application/json',
'Accept-Language': 'en-US,en;q=0.9',
'Cache-Control': 'no-cache',
'X-Request-ID': 'demo-' + Math.random().toString(36).substr(2, 9)
}
}, (res) => {
console.log(`\nResponse Status: ${res.statusCode} ${res.statusMessage}`);
console.log('Response Headers:', JSON.stringify(res.headers, null, 2));
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('\nResponse received. Check your browser at http://localhost:3006 for the complete output.');
// Make another request with form data to show different headers
console.log('\nMaking a POST request with form data...');
const postData = 'username=testuser&password=testpass';
const postReq = http.request({
hostname: 'localhost',
port: PORT,
path: '/submit',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData),
'X-Requested-With': 'XMLHttpRequest',
'Referer': 'http://localhost:3006/'
}
}, (res) => {
console.log(`\nForm POST Response Status: ${res.statusCode}`);
res.resume();
// Close the server after all tests
res.on('end', () => {
console.log('\nTests completed. Server will keep running.');
console.log('Visit http://localhost:3006 in your browser to see the headers.');
});
});
postReq.on('error', (e) => {
console.error(`Form POST error: ${e.message}`);
});
// Write data to request body
postReq.write(postData);
postReq.end();
});
});
req.on('error', (e) => {
console.error(`Request error: ${e.message}`);
server.close();
});
req.end();
});
// Handle server errors
server.on('error', (err) => {
console.error('Server error:', err);
});
// Handle process termination
process.on('SIGINT', () => {
console.log('\nShutting down server...');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});