What if you could run your own web server with just a few lines of code?
Creating a basic HTTP server in Node.js - Why You Should Know This
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you want to share a simple message or webpage with your friends over the internet by running your own server on your computer.
You try to handle all the network details yourself, like listening for requests, reading data, and sending responses.
Doing all the network communication manually is very complicated and easy to get wrong.
You have to manage low-level details like TCP connections, data streams, and protocols, which can be confusing and error-prone.
This makes building even a simple server slow and frustrating.
Node.js provides a built-in HTTP module that lets you create a basic web server with just a few lines of code.
This module handles all the complex network details for you, so you can focus on what your server should do.
Open TCP socket, parse HTTP request manually, write HTTP response bytes
const http = require('http'); http.createServer((req, res) => { res.end('Hello World'); }).listen(3000);
You can quickly build and run your own web server to share content, test ideas, or learn how the web works.
Running a local server to test your website during development before publishing it online.
Manually handling network communication is complex and error-prone.
Node.js HTTP module simplifies creating servers with minimal code.
This lets you focus on your app's logic, not low-level details.
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
