const http = require('http');
// Create a simple HTTP server for testing
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from the test server!');
});
// Start the test server
server.listen(0, 'localhost', () => {
const port = server.address().port;
console.log(`Test server running at http://localhost:${port}`);
// Create a client request
console.log('\nCreating a GET request to the test server...');
const req = http.request({
hostname: 'localhost',
port: port,
path: '/test',
method: 'GET',
headers: {
'User-Agent': 'Node.js Demo Client',
'Accept': 'text/plain'
}
}, (res) => {
console.log(`\nResponse received with status code: ${res.statusCode}`);
// Log response headers
console.log('\nResponse Headers:');
console.log(JSON.stringify(res.headers, null, 2));
// Collect response data
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
// When all data is received
res.on('end', () => {
console.log('\nResponse Body:');
console.log(data);
// Close the test server
server.close(() => {
console.log('\nTest server closed');
});
});
}).on('error', (err) => {
console.error('Request error:', err);
server.close();
});
// Log request headers
console.log('\nRequest Headers:');
console.log(JSON.stringify(req.getHeaders(), null, 2));
// Handle request events
req.on('socket', () => {
console.log('\nSocket assigned to request');
});
req.on('connect', () => {
console.log('Connected to server');
});
req.on('abort', () => {
console.log('Request aborted');
});
// End the request
console.log('\nSending request...');
req.end();
});
// Handle server errors
server.on('error', (err) => {
console.error('Server error:', err);
});