简体   繁体   中英

Caching of node/express GET request on server side with JSON body

I am trying to get a simple server-side cache up-and-running within node/express with a GET request. Managed to get this working when dealing with simple URL parameters, but not sure how to approach it with a JSON body.

This is what I have thus far for the URL parameter version:

const mcache = require('memory-cache');
app.set('view engine', 'jade');

const cache = (duration) => {
  return (req, res, next) => {
    let key = '__express__' + req.originalUrl || req.url;
    let cachedBody = mcache.get(key);
    if (cachedBody) {
      res.send(cachedBody);
      return;
    } else {
      res.sendResponse = res.send;
      res.send = (body) => {
        mcache.put(key, body, duration * 1000);
        res.sendResponse(body);
      };
      next();
    }
  };
};

app.get('/user/:id', cache(10), (req, res) => {
  setTimeout(() => {
    if (req.params.id == 1) {
      res.json({ id: 1, name: 'John' });
    } else if (req.params.id == 2) {
      res.json({ id: 2, name: 'Bob' });
    } else if (req.params.id == 3) {
      res.json({ id: 3, name: 'Stuart' });
    }
  }, 3000); //setTimeout was used to simulate a slow processing request
});

Any pointers?

For sure in your cache middleware you shouldn't be using res.send because you can only perform one response per request. So before you get to res.json in your app.get , res is already send.

I assume that you want to pass the data with that res.send to the app.get ? If so you can either pass it inside next() or use res.locals like res.locals.varName = catchedBody and then you can use that inside your app.get function because it will be available during entire http request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM