Routing Without Framework
NodeJS
Hard
4 views
Problem Description
Handle /, /health, and 404 using if statements.
Output Format
Start server code.
Constraints
Return JSON for /health.
Official Solution
const http = require('http');
const server = http.createServer((req, res) => {
const url = req.url || '/';
if (url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
return res.end('meetcode home');
}
if (url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ ok: true }));
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
});
server.listen(3001, () => console.log('http://localhost:3001'));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!