const http = require('http');
const querystring = require('querystring');
// Create a test server to demonstrate POST requests
const server = http.createServer((req, res) => {
if (req.method === 'POST') {
let body = [];
// Collect request data
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// Parse the request body based on content type
let parsedBody = {};
const contentType = req.headers['content-type'] || '';
try {
if (contentType.includes('application/json')) {
parsedBody = JSON.parse(body);
} else if (contentType.includes('application/x-www-form-urlencoded')) {
parsedBody = querystring.parse(body);
} else {
parsedBody = { raw: body };
}
} catch (e) {
parsedBody = { error: 'Failed to parse request body', raw: body };
}
// Prepare response
const responseData = {
status: 'success',
method: req.method,
url: req.url,
headers: req.headers,
body: parsedBody
};
// Send JSON response
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(responseData, null, 2));
});
} else {
res.writeHead(405, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
status: 'error',
message: 'Method Not Allowed. Use POST.'
}));
}
});
// Start the server
const PORT = 3005;
server.listen(PORT, () => {
console.log(`Test server running at http://localhost:${PORT}`);
// Test data
const postData = {
name: 'John Doe',
email: 'john@example.com',
message: 'This is a test message from the demo',
timestamp: new Date().toISOString()
};
// Convert data to JSON string
const jsonData = JSON.stringify(postData);
// Make a POST request with JSON data
console.log('\nMaking a POST request with JSON data...');
const options = {
hostname: 'localhost',
port: PORT,
path: '/api/data',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(jsonData),
'X-Request-ID': 'demo-12345'
}
};
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 responseData = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
responseData += chunk;
});
res.on('end', () => {
console.log('\nResponse Body:');
console.log(responseData);
// 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();
});
// Write data to request body
req.write(jsonData);
req.end();
});
// Handle server errors
server.on('error', (err) => {
console.error('Server error:', err);
});