Webserver

Overview

data desktop

Javascript Serer

const http = require('node:http'); const url = require('node:url'); const hostname = '127.0.0.1'; const port = 3000; // Create the web server const server = http.createServer((req, res) => { // Parse the URL to get the path (e.g., '/about' or '/contact') const parsedUrl = url.parse(req.url, true); const path = parsedUrl.pathname; // Set the response header to JSON format res.setHeader('Content-Type', 'application/json'); // Route handling logic (Registering paths) if (path === '/' || path === '/home') { res.statusCode = 200; res.end(JSON.stringify({ message: 'Welcome to the Home Page!' })); } else if (path === '/api/user') { res.statusCode = 200; res.end(JSON.stringify({ id: 1, name: 'Alex', role: 'Developer' })); } else if (path === '/about') { res.statusCode = 200; res.end(JSON.stringify({ message: 'This is the About Page.' })); } else { // 404 Not Found fallback if the path doesn't match anything above res.statusCode = 404; res.end(JSON.stringify({ error: 'Route not found' })); } }); // Start the server server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });