Read JSON Body
NodeJS
Hard
3 views
Problem Description
Read request body, parse JSON, and echo it back.
Output Format
Start server code.
Constraints
Handle invalid JSON by returning 400.
Official Solution
const http = require('http');
function readBody(req) {
return new Promise((resolve) => {
let data = '';
req.on('data', (chunk) => { data += chunk; });
req.on('end', () => resolve(data));
});
}
const server = http.createServer(async (req, res) => {
if (req.method !== 'POST') {
res.writeHead(405, { 'Content-Type': 'text/plain' });
return res.end('POST only');
}
const text = await readBody(req);
try {
const obj = JSON.parse(text || '{}');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ meetcode: true, data: obj }));
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
server.listen(3002, () => console.log('http://localhost:3002'));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!