Read JSON Body

Read JSON Body

Hard NodeJS HTTP & APIs 26 views
Explanation Complexity

Problem Statement

Read request body, parse JSON, and echo it back.

Input Format

No input.

Output Format

Start server code.

Constraints

Handle invalid JSON by returning 400.

Input / Output Format

Input Format
No input.
Output Format
Start server code.
Constraints
Handle invalid JSON by returning 400.

Example Solution (Public)

NodeJS
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'));

Official Solution Code

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'));
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.