Bird
Raised Fist0
Node.jsframework~20 mins

Creating a basic HTTP server in Node.js - Practice Exercises

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Node.js HTTP Server Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this basic HTTP server response?
Consider this Node.js HTTP server code. What will the server send back to the client when accessed?
Node.js
import http from 'http';
const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, world!');
});
server.listen(3000);
AThe server responds with JSON: { message: 'Hello, world!' }
BThe server responds with plain text: 'Hello, world!'
CThe server responds with HTML content containing 'Hello, world!'
DThe server throws an error because of missing response end
Attempts:
2 left
💡 Hint
Look at the content type and the string passed to res.end.
📝 Syntax
intermediate
2:00remaining
Which option contains a syntax error in creating an HTTP server?
Identify the option that will cause a syntax error when creating a basic HTTP server in Node.js.
A;)0003(netsil.revres ;)} ;)'iH'(dne.ser { >= )ser ,qer((revreSetaerc.ptth = revres tsnoc ;'ptth' morf ptth tropmi
Bconst http = require('http'); const server = http.createServer((req, res) => { res.end('Hi'); }); server.listen(3000);
Cimport http from 'http'; const server = http.createServer((req, res) => { res.end('Hi'); }); server.listen(3000);
Dmport http from 'http'; const server = http.createServer((req, res) => { res.end('Hi'); }); server.listen(3000);
Attempts:
2 left
💡 Hint
Look for missing punctuation or misplaced code inside the callback.
state_output
advanced
2:00remaining
What is the value of 'count' after 3 client requests?
This server counts how many requests it has handled. What is the value of 'count' after 3 requests?
Node.js
import http from 'http';
let count = 0;
const server = http.createServer((req, res) => {
  count++;
  res.end(`Request number: ${count}`);
});
server.listen(3000);
A3
B1
C0
DUndefined
Attempts:
2 left
💡 Hint
The count variable increases each time the server handles a request.
🔧 Debug
advanced
2:00remaining
Which option causes the server to crash on request?
One of these server codes will crash when a client makes a request. Identify which one.
Aimport http from 'http'; const server = http.createServer((req, res) => { res.end('OK'); res.end('Again'); }); server.listen(3000);
Bimport http from 'http'; const server = http.createServer((req, res) => { res.end('OK'); }); server.listen(3000);
Cimport http from 'http'; const server = http.createServer((req, res) => { res.write('OK'); }); server.listen(3000);
Dimport http from 'http'; const server = http.createServer((req, res) => { res.statusCode = 200; res.end('OK'); }); server.listen(3000);
Attempts:
2 left
💡 Hint
Check if the response is properly ended.
🧠 Conceptual
expert
2:00remaining
What happens if server.listen is called twice on the same port?
Consider calling server.listen(3000) twice on the same HTTP server instance. What will happen?
AThe server listens twice on port 3000 without error.
BThe server restarts and resets all state.
CThe server silently ignores the second listen call.
DThe second call throws an error because the port is already in use.
Attempts:
2 left
💡 Hint
Ports can only be bound once per server instance.

Practice

(1/5)
1. What does the http.createServer() function do in Node.js?
easy
A. It compiles JavaScript code into machine code.
B. It creates a database connection for storing data.
C. It creates a server that listens for HTTP requests and sends responses.
D. It formats JSON data for sending over the network.

Solution

  1. Step 1: Understand the purpose of http.createServer()

    This function sets up a server that waits for HTTP requests from clients like browsers.
  2. 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.
  3. Final Answer:

    It creates a server that listens for HTTP requests and sends responses. -> Option C
  4. Quick Check:

    HTTP server creation = It creates a server that listens for HTTP requests and sends responses. [OK]
Hint: Remember: createServer sets up the web server [OK]
Common Mistakes:
  • Confusing server creation with database connection
  • Thinking it compiles code
  • Mixing up data formatting with server setup
2. Which of the following is the correct way to start a Node.js HTTP server on port 3000?
easy
A. http.listen(3000);
B. server.listen(3000);
C. server.start(3000);
D. server.run(3000);

Solution

  1. Step 1: Identify the method to start the server

    The correct method to make the server listen on a port is listen().
  2. Step 2: Match the method with the server object

    Calling server.listen(3000); starts the server on port 3000.
  3. Final Answer:

    server.listen(3000); -> Option B
  4. Quick Check:

    Start server with listen() = server.listen(3000); [OK]
Hint: Use listen() to start the server on a port [OK]
Common Mistakes:
  • Using non-existent methods like start() or run()
  • Calling listen() on http instead of server
  • Confusing server methods with other modules
3. What will the following Node.js code output when accessed via a browser?
const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World');
});
server.listen(4000);
medium
A. Hello World
B. Error: server.listen is not a function
C. 404 Not Found
D. Hello

Solution

  1. 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.
  2. Step 2: Understand what the browser receives

    When accessed, the browser will display the exact string 'Hello World' from the server response.
  3. Final Answer:

    Hello World -> Option A
  4. Quick Check:

    Response text = Hello World [OK]
Hint: Check res.end() content for output text [OK]
Common Mistakes:
  • Expecting an error due to incorrect method
  • Confusing status codes with output text
  • Assuming partial output without reading res.end()
4. Identify the error in this Node.js HTTP server code:
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');
medium
A. Incorrect Content-Type header value
B. Using res.write() without res.end() causes error
C. Missing semicolon after server.listen(8080)
D. No error; code runs correctly and serves 'Welcome'

Solution

  1. Step 1: Check syntax and method usage

    The code correctly calls res.write() followed by res.end(), which is valid to send response data.
  2. 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.
  3. Final Answer:

    No error; code runs correctly and serves 'Welcome' -> Option D
  4. Quick Check:

    Valid server code = No error; code runs correctly and serves 'Welcome' [OK]
Hint: res.write() + res.end() is valid to send response [OK]
Common Mistakes:
  • Thinking missing semicolons cause errors
  • Believing res.write() must be avoided
  • Assuming wrong Content-Type causes failure
5. You want to create a Node.js HTTP server that responds with JSON data {"status":"ok"} and sets the correct header. Which code snippet correctly does this?
hard
A. const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify({status: 'ok'})); });
B. const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('{"status":"ok"}'); });
C. const server = http.createServer((req, res) => { res.writeHead(404, {'Content-Type': 'application/json'}); res.end(JSON.stringify({status: 'ok'})); });
D. const server = http.createServer((req, res) => { res.writeHead(200); res.end({status: 'ok'}); });

Solution

  1. Step 1: Set correct Content-Type header for JSON

    The header must be 'application/json' to tell the client the response is JSON data.
  2. Step 2: Send JSON string as response body

    Use JSON.stringify() to convert the object to a JSON string before sending with res.end().
  3. Final Answer:

    Code snippet with application/json header and JSON.stringify() -> Option A
  4. Quick 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]
Hint: Use application/json header and JSON.stringify() [OK]
Common Mistakes:
  • Sending object directly without stringifying
  • Using wrong Content-Type header
  • Sending JSON string with text/plain header
  • Using 404 status instead of 200