We create an HTTP server to listen for requests from web browsers or other clients and send back responses like web pages or data.
Creating a basic HTTP server in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
import http from 'http'; const server = http.createServer((req, res) => { // handle request and response here }); server.listen(3000, () => { console.log(`Server running on port 3000`); });
The http.createServer function creates a server that listens for requests.
The callback receives req (request) and res (response) objects to handle communication.
import http from 'http'; const server = http.createServer((req, res) => { res.end('Hello World'); }); server.listen(3000);
import http from 'http'; const server = http.createServer((req, res) => { if (req.url === '/') { res.end('Home page'); } else { res.statusCode = 404; res.end('Not found'); } }); server.listen(8080);
This program creates a simple HTTP server on port 4000. It sends a plain text message 'Welcome to my server!' for every request. When the server starts, it logs a message to the console.
import http from 'http'; const port = 4000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Welcome to my server!'); }); server.listen(port, () => { console.log(`Server running on port ${port}`); });
Always set the correct Content-Type header so browsers know how to display the response.
Use res.end() to finish the response and send data back to the client.
Remember to choose a port number that is free and allowed by your system.
Creating an HTTP server lets your computer respond to web requests.
Use http.createServer with a function to handle requests and responses.
Start the server with server.listen(port) and check the console for confirmation.
Practice
http.createServer() function do in Node.js?Solution
Step 1: Understand the purpose of
This function sets up a server that waits for HTTP requests from clients like browsers.http.createServer()Step 2: Identify what the server does
The server uses a function to handle incoming requests and send back responses, enabling communication over the web.Final Answer:
It creates a server that listens for HTTP requests and sends responses. -> Option CQuick Check:
HTTP server creation = It creates a server that listens for HTTP requests and sends responses. [OK]
- Confusing server creation with database connection
- Thinking it compiles code
- Mixing up data formatting with server setup
Solution
Step 1: Identify the method to start the server
The correct method to make the server listen on a port islisten().Step 2: Match the method with the server object
Callingserver.listen(3000);starts the server on port 3000.Final Answer:
server.listen(3000); -> Option BQuick Check:
Start server with listen() = server.listen(3000); [OK]
- Using non-existent methods like start() or run()
- Calling listen() on http instead of server
- Confusing server methods with other modules
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World');
});
server.listen(4000);Solution
Step 1: Analyze the server response setup
The server sets the HTTP status to 200 (OK) and content type to plain text, then sends 'Hello World' as the response body.Step 2: Understand what the browser receives
When accessed, the browser will display the exact string 'Hello World' from the server response.Final Answer:
Hello World -> Option AQuick Check:
Response text = Hello World [OK]
- Expecting an error due to incorrect method
- Confusing status codes with output text
- Assuming partial output without reading res.end()
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Welcome');
res.end();
});
server.listen(8080)
console.log('Server running on port 8080');Solution
Step 1: Check syntax and method usage
The code correctly calls res.write() followed by res.end(), which is valid to send response data.Step 2: Verify headers and server start
The Content-Type is valid as 'text/html', and server.listen(8080) starts the server properly. Missing semicolons are optional in JavaScript.Final Answer:
No error; code runs correctly and serves 'Welcome' -> Option DQuick Check:
Valid server code = No error; code runs correctly and serves 'Welcome' [OK]
- Thinking missing semicolons cause errors
- Believing res.write() must be avoided
- Assuming wrong Content-Type causes failure
{"status":"ok"} and sets the correct header. Which code snippet correctly does this?Solution
Step 1: Set correct Content-Type header for JSON
The header must be 'application/json' to tell the client the response is JSON data.Step 2: Send JSON string as response body
UseJSON.stringify()to convert the object to a JSON string before sending withres.end().Final Answer:
Code snippet with application/json header and JSON.stringify() -> Option AQuick Check:
JSON header + stringified data = const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify({status: 'ok'})); }); [OK]
- Sending object directly without stringifying
- Using wrong Content-Type header
- Sending JSON string with text/plain header
- Using 404 status instead of 200
