const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
// 'req' is the IncomingMessage object (request)
console.log('Request URL:', req.url);
console.log('Request Method:', req.method);
console.log('HTTP Version:', req.httpVersion);
// Headers
console.log('Headers:', req.headers);
console.log('User-Agent:', req.headers['user-agent']);
// Raw headers with keys and values as separate array elements
console.log('Raw Headers:', req.rawHeaders);
// Socket information
console.log('Remote Address:', req.socket.remoteAddress);
console.log('Remote Port:', req.socket.remotePort);
// Reading the message body (if any)
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
});
req.on('end', () => {
body = Buffer.concat(body).toString();
console.log('Request body:', body);
// Now that we have the body, send a response
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
httpVersion: req.httpVersion,
method: req.method,
url: req.url,
headers: req.headers,
body: body || null
}));
});
// Handle errors
req.on('error', (err) => {
console.error('Request error:', err);
res.statusCode = 400;
res.end('Error: ' + err.message);
});
});
// Start server
const PORT = 8080;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
// Make a test request
const testReq = http.request({
hostname: 'localhost',
port: PORT,
path: '/test?param1=value1¶m2=value2',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Custom-Header': 'Custom Value'
}
}, (res) => {
let responseData = '';
res.on('data', (chunk) => {
responseData += chunk;
});
res.on('end', () => {
console.log('Test request response:', JSON.parse(responseData));
server.close();
});
});
testReq.on('error', (err) => {
console.error('Test request error:', err);
server.close();
});
testReq.end('{"message":"Hello from the client!"}');
});
// Handle server errors
server.on('error', (err) => {
console.error('Server error:', err);
});