const http = require('http');
// Create a test server to demonstrate GET requests
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
// Set response headers
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Custom-Header', 'Test-Value');
// Send response
res.writeHead(200, 'OK');
res.end(`
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
</head>
<body>
<h1>Hello from the test server!</h1>
<p>This is a test response for a GET request.</p>
<p>Request URL: ${req.url}</p>
</body>
</html>
`);
} else {
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Method Not Allowed');
}
});
// Start the server
const PORT = 3004;
server.listen(PORT, () => {
console.log(`Test server running at http://localhost:${PORT}`);
// Make a GET request to the test server
console.log('\nMaking a GET request to the test server...');
const options = {
hostname: 'localhost',
port: PORT,
path: '/test?param=value',
method: 'GET',
headers: {
'User-Agent': 'Node.js Demo Client',
'Accept': 'text/html',
'X-Requested-With': 'XMLHttpRequest'
}
};
const req = http.request(options, (res) => {
console.log(`\nResponse Status: ${res.statusCode} ${res.statusMessage}`);
console.log('Response Headers:', JSON.stringify(res.headers, null, 2));
let responseBody = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
responseBody += chunk;
});
res.on('end', () => {
console.log('\nResponse Body:');
console.log(responseBody.substring(0, 200) + '... [truncated]');
// Close the server after receiving the response
server.close(() => {
console.log('\nTest server closed');
});
});
});
// Handle request errors
req.on('error', (e) => {
console.error(`Request error: ${e.message}`);
server.close();
});
// End the request
req.end();
});
// Handle server errors
server.on('error', (err) => {
console.error('Server error:', err);
});
Test server running at http://localhost:3004 Making a GET request to the test server... Response Status: 200 OK Response Headers: { "content-type": "text/html", "x-custom-header": "Test-Value", "date": "Wed, 18 Jun 2025 06:40:38 GMT", "connection": "close", "transfer-encoding": "chunked" } Response Body:Test Page Hello from the test server!
This is a test response for a GET request.
Request URL: /test?param=value
... [truncated] Test server closed