Imagine your Express server handles many requests for the same data. How does caching help reduce the server's work?
Think about how remembering answers helps you avoid repeating work.
Caching keeps a copy of data so the server can reuse it quickly. This avoids repeated calculations or database calls, making responses faster and reducing server load.
Consider an Express route that caches API responses. What is the main effect on response time when a cached response is available?
app.get('/data', (req, res) => { if (cache.has('data')) { res.send(cache.get('data')); } else { const data = fetchDataFromDB(); cache.set('data', data); res.send(data); } });
Think about skipping the slowest step.
Serving cached data skips the database call, which is usually slower. This makes the response faster.
Look at this Express caching code. Why might users see outdated data?
const cache = new Map(); app.get('/info', (req, res) => { if (cache.has('info')) { res.send(cache.get('info')); } else { const info = fetchLatestInfo(); cache.set('info', info); res.send(info); } });
Think about how long cached data stays valid.
Without a way to expire or refresh the cache, the server keeps sending old data, causing stale responses.
Choose the code that properly caches and sends JSON data in Express.
Remember Express has a method to send JSON directly.
Option A caches the user object and uses res.json() to send JSON properly. Other options mix stringifying and parsing incorrectly or send raw objects improperly.
Given this Express caching code, what is the content of cache after three requests to /count?
const cache = {};
app.get('/count', (req, res) => {
if (!cache.count) {
cache.count = 1;
} else {
cache.count += 1;
}
res.send(`Count is ${cache.count}`);
});Each request increases the count by one if cached.
The cache starts empty. First request sets count to 1. Second increments to 2. Third increments to 3. So cache.count is 3 after three requests.