Q1. How do you build a REST API with pure Node.js?
Create an HTTP server, parse the request method and URL, implement CRUD operations. Example:
if (req.method === 'GET' && req.url === '/api/users') { // return users } else if (req.method === 'POST' && req.url === '/api/users') { // parse body, create user }. Handle JSON parsing and responses.Q2. How do you parse JSON request bodies for API endpoints?
Collect data chunks as described earlier, then after 'end' event, parse with JSON.parse(body). Handle errors for invalid JSON. Example:
let body = ''; req.on('data', chunk => { body += chunk; }).on('end', () => { try { const data = JSON.parse(body); // process } catch (err) { res.statusCode = 400; res.end('Invalid JSON'); } });Q3. How do you implement routing for REST API?
Create a routing table mapping patterns to handlers. For resource-based routing, use patterns like '/api/users/:id'. Extract ID from URL. Example:
const match = req.url.match(/^/api/users/(d+)$/); if (match) { const id = match[1]; // handle /api/users/123 }. This supports dynamic routes.Q4. How do you send proper HTTP status codes for API responses?
Set res.statusCode appropriately: 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 500 Internal Server Error. Also set Content-Type: application/json. Example:
res.statusCode = 201; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(newUser));Q5. How do you handle CORS in a pure Node.js API?
Set CORS headers on responses:
res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); For preflight OPTIONS requests, respond with 200 and appropriate headers. This allows browsers to access your API from different origins.