Complete the code to create a basic HTTP server that listens on port 3000.
const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World'); }); server.listen([1], () => { console.log('Server running'); });
The server listens on port 3000, which is a common port for local development.
Complete the code to check the request URL and respond with 'Home Page' if the path is '/'.
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === [1]) { res.statusCode = 200; res.end('Home Page'); } else { res.statusCode = 404; res.end('Not Found'); } }); server.listen(3000);
The root path '/' is used to represent the home page URL.
Fix the error in the code to respond with 'About Page' when the URL is '/about'.
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === [1]) { res.statusCode = 200; res.end('About Page'); } else { res.statusCode = 404; res.end('Not Found'); } }); server.listen(3000);
The URL path must start with a slash '/' to match the request URL correctly.
Fill both blanks to respond with JSON data when the URL is '/api/data'.
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === [1]) { res.statusCode = 200; res.setHeader('Content-Type', [2]); res.end(JSON.stringify({ message: 'Hello API' })); } else { res.statusCode = 404; res.end('Not Found'); } }); server.listen(3000);
The URL must match '/api/data' exactly, and the Content-Type header should be 'application/json' to indicate JSON data.
Fill all three blanks to route requests to different responses for '/', '/about', and '/contact'.
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === [1]) { res.end('Home Page'); } else if (req.url === [2]) { res.end('About Page'); } else if (req.url === [3]) { res.end('Contact Page'); } else { res.statusCode = 404; res.end('Not Found'); } }); server.listen(3000);
Each URL path must match exactly the route to respond with the correct page.