0
0
Node.jsframework~10 mins

Long polling as fallback in Node.js - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Ahttp
B3000
Clocalhost
Dserver
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string like 'http' instead of a port number.
Passing the server object instead of a port.
2fill in blank
medium

Complete 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'
A'application/json'
B'text/html'
C'text/plain'
D'image/png'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'text/html' when sending JSON data.
Forgetting to set the Content-Type header.
3fill in blank
hard

Fix 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'
AwriteHead
Bwrite
Csend
Dend
Attempts:
3 left
💡 Hint
Common Mistakes
Using res.write() without ending the response.
Using res.send() which is not a native Node.js method.
4fill in blank
hard

Fill 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'
AlongPoll
BsendData
C5000
D1000
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a wrong function name.
Using too long or too short timeout values.
5fill in blank
hard

Fill 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'
A'application/json'
Bend
Cwrite
D'text/plain'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'text/plain' instead of 'application/json' for JSON data.
Using res.write() without ending the response.