Homework & Coding Practice
Homework/Practice Coding Assignment (20-min)
Task: Create an HTTP Server That Serves Different Messages Based on Routes
Step-by-Step Procedure:
Step 1: Create a File Named
multiRouteServer.js:Write the following code:
const http = require('http'); const server = http.createServer((req, res) => { console.log(`Request Method: ${req.method}, URL: ${req.url}`); if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Welcome to the Home Page'); } else if (req.url === '/about') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('This is the About Page'); } else if (req.url === '/contact') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Contact us at [email protected]'); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found'); } }); server.listen(3000, () => { console.log('Server running at http://localhost:3000'); });
Step 2: Run the Server:
Open the terminal and run:
//bash node multiRouteServer.js
Step 3: Test the Server:
Use Postman or a browser to test the following routes:
GET
http://localhost:3000/: Returns "Welcome to the Home Page".GET
http://localhost:3000/about: Returns "This is the About Page".GET
http://localhost:3000/contact: Returns "Contact us at [email protected]".GET
http://localhost:3000/unknown: Returns "404 Not Found".
Step 4: Observe the Logs:
Check the terminal for logs showing the request method and URL for each request.
Expected Outcomes
Students build a basic understanding of HTTP servers and REST principles.
Students gain hands-on experience with routing and debugging HTTP requests.
Homework reinforces learning through practical implementation of multi-route servers.
Last updated