Complete the code to set a cache-control header that tells browsers to cache the response for 1 hour.
app.get('/data', (req, res) => { res.set('Cache-Control', '[1]'); res.send('Cached data'); });
Setting Cache-Control to public, max-age=3600 tells browsers to cache the response for 3600 seconds (1 hour), improving performance by avoiding repeated requests.
Complete the code to use an in-memory cache object to store and return data if available.
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);
});The cache key is 'info', so to return cached data, use cache['info']. This avoids recomputing or fetching data again, improving response time.
Fix the error in the middleware that caches responses by completing the missing method to send the cached data.
const cache = {};
app.use((req, res, next) => {
if (cache[req.url]) {
return res.[1](cache[req.url]);
}
next();
});res.write() without ending the response causes hanging requests.The res.send() method sends the cached response to the client properly. Using write or end alone won't set headers or finish the response correctly.
Fill both blanks to create a cache key using the request method and URL.
app.use((req, res, next) => {
const key = req.[1] + ':' + req.[2];
if (cache[key]) {
return res.send(cache[key]);
}
next();
});req.path alone misses query parameters, causing cache misses.Using req.method and req.url creates a unique cache key for each HTTP method and URL combination, ensuring correct cached responses.
Fill all three blanks to store the response data in cache and send it after the original send method.
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();
});We save the original res.send method in originalSend (option A). Then override res.send (option B) to cache the body (option C) before sending it. This caches responses transparently.