Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
const http = require('http'); const server = http.createServer((req, res) => { const { method, url } = req; // Simple router: if (url === '/' && method === 'GET') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<h1>Home Page</h1>'); } else if (url === '/api/users' && method === 'GET') { const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, ]; res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(users)); } else if (url === '/api/users' && method === 'POST') { let body = ''; req.on('data', chunk => { body += chunk; }); req.on('end', () => { const newUser = JSON.parse(body); console.log('New user:', newUser); res.writeHead(201, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Created', user: newUser })); }); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found'); } }); server.listen(3000, () => console.log('Server on port 3000'));
Result
Open