const http = require('http'); const server = http.createServer((req, res) => { const { url } = req; if (url === '/html') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<h1>Welcome to the HTML response</h1>'); } else if (url === '/json') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'This is a JSON response', status: 'success' })); } else if (url === '/text') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('This is a plain text response.'); } else if (url === '/js') { res.writeHead(200, { 'Content-Type': 'application/javascript' }); res.end('console.log("JavaScript response from server");'); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Resource not found'); } }); server.listen(3000, () => { console.log('Server running at http://localhost:3000'); });
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter