Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a simple HTTP server in Node.js.
Node.js
const http = require('http'); const server = http.createServer((req, res) => { res.end('Hello World'); }); server.listen([1]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string like 'http' instead of a port number.
Passing the server object instead of a port.
✗ Incorrect
The server.listen method requires a port number to start the server. 3000 is a common choice.
2fill in blank
mediumComplete the code to set the response header for JSON content.
Node.js
res.writeHead(200, { 'Content-Type': [1] });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'text/html' when sending JSON data.
Forgetting to set the Content-Type header.
✗ Incorrect
For JSON responses, the Content-Type header should be 'application/json'.
3fill in blank
hardFix the error in the long polling function to correctly send a response when data is ready.
Node.js
function longPoll(req, res) {
if (dataReady) {
res.[1](JSON.stringify({ message: 'Data ready' }));
} else {
// wait and retry
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using res.write() without ending the response.
Using res.send() which is not a native Node.js method.
✗ Incorrect
The res.end() method sends the response and closes the connection, which is needed here.
4fill in blank
hardFill both blanks to correctly implement a long polling retry with a timeout.
Node.js
function longPoll(req, res) {
if (dataReady) {
res.end(JSON.stringify({ data: 'Here is your data' }));
} else {
setTimeout(() => {
[1](req, res);
}, [2]);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a wrong function name.
Using too long or too short timeout values.
✗ Incorrect
The function calls itself after 1000 milliseconds (1 second) to retry the long polling.
5fill in blank
hardFill all three blanks to create a fallback long polling server that responds with JSON data.
Node.js
const http = require('http'); let dataReady = false; const server = http.createServer((req, res) => { if (req.url === '/poll') { res.writeHead(200, { 'Content-Type': [1] }); if (dataReady) { res.[2](JSON.stringify({ status: 'ready' })); dataReady = false; } else { setTimeout(() => { res.[3](JSON.stringify({ status: 'timeout' })); }, 3000); } } else { res.writeHead(404); res.end(); } }); server.listen(8080);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'text/plain' instead of 'application/json' for JSON data.
Using res.write() without ending the response.
✗ Incorrect
The server sets the JSON content type and uses res.end() to send and close the response in both cases.