0
0
Expressframework~10 mins

Why caching improves performance in Express - Test Your Understanding

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

Complete the code to set a cache-control header that tells browsers to cache the response for 1 hour.

Express
app.get('/data', (req, res) => {
  res.set('Cache-Control', '[1]');
  res.send('Cached data');
});
Drag options to blanks, or click blank then click option'
Apublic, max-age=3600
Bno-cache
Cno-store
Dprivate, max-age=0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'no-cache' disables caching, which hurts performance.
2fill in blank
medium

Complete the code to use an in-memory cache object to store and return data if available.

Express
const cache = {};
app.get('/info', (req, res) => {
  if (cache['info']) {
    return res.send(cache['[1]']);
  }
  const data = 'Fresh info';
  cache['info'] = data;
  res.send(data);
});
Drag options to blanks, or click blank then click option'
Areq
Bdata
Cinfo
Dcache
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong key like 'data' or 'cache' causes undefined results.
3fill in blank
hard

Fix the error in the middleware that caches responses by completing the missing method to send the cached data.

Express
const cache = {};
app.use((req, res, next) => {
  if (cache[req.url]) {
    return res.[1](cache[req.url]);
  }
  next();
});
Drag options to blanks, or click blank then click option'
Asend
Bwrite
Cjson
Dend
Attempts:
3 left
💡 Hint
Common Mistakes
Using res.write() without ending the response causes hanging requests.
4fill in blank
hard

Fill both blanks to create a cache key using the request method and URL.

Express
app.use((req, res, next) => {
  const key = req.[1] + ':' + req.[2];
  if (cache[key]) {
    return res.send(cache[key]);
  }
  next();
});
Drag options to blanks, or click blank then click option'
Amethod
Burl
Cpath
Dquery
Attempts:
3 left
💡 Hint
Common Mistakes
Using req.path alone misses query parameters, causing cache misses.
5fill in blank
hard

Fill all three blanks to store the response data in cache and send it after the original send method.

Express
app.use((req, res, next) => {
  const key = req.method + ':' + req.url;
  const originalSend = res.[1];
  res.[2] = function (body) {
    cache[key] = body;
    return originalSend.call(this, [3]);
  };
  next();
});
Drag options to blanks, or click blank then click option'
Asend
Cbody
Dres
Attempts:
3 left
💡 Hint
Common Mistakes
Calling originalSend without .call or passing wrong argument causes errors.