Complete the code to create a basic HTTP server in Node.js.
const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end([1]); }); server.listen(3000, () => { console.log('Server running on port 3000'); });
The server responds with 'Hello World!' text to any request.
Complete the code to listen on port 8080 instead of 3000.
server.listen([1], () => { console.log('Server running on port 8080'); });
Port 8080 is commonly used for HTTP servers during development.
Fix the error in the code to properly import the HTTP module using modern ES modules syntax.
import [1] from 'http'; const server = http.createServer((req, res) => { res.end('Hi'); });
Using 'import * as http from "http";' correctly imports the entire module as an object.
Fill both blanks to send a JSON response with status code 200.
const server = http.createServer((req, res) => {
res.statusCode = [1];
res.setHeader('Content-Type', [2]);
res.end(JSON.stringify({ message: 'Success' }));
});Status code 200 means OK, and 'application/json' tells the browser the response is JSON.
Fill all three blanks to create a server that responds with HTML content on port 5000.
const server = http.createServer((req, res) => {
res.statusCode = [1];
res.setHeader('Content-Type', [2]);
res.end([3]);
});
server.listen(5000, () => {
console.log('Server running on port 5000');
});The server sends a 200 OK status, sets the content type to HTML, and sends a simple HTML heading.