【问题标题】:Caching of node/express GET request on server side with JSON body使用 JSON 正文在服务器端缓存节点/express GET 请求
【发布时间】:2020-09-01 03:41:45
【问题描述】:

我正在尝试通过 GET 请求在 node/express 中启动并运行一个简单的服务器端缓存。在处理简单的 URL 参数时设法让它工作,但不确定如何使用 JSON 正文来处理它。

这就是我迄今为止的 URL 参数版本:

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
});

任何指针?

【问题讨论】:

    标签: javascript node.js api express caching


    【解决方案1】:

    当然,在您的缓存中间件中,您不应该使用res.send,因为每个请求只能执行一个响应。因此,在您到达 res.json 中的 app.get 之前, res 已经发送。

    我假设您想将带有res.send 的数据传递给app.get?如果是这样,您可以在 next() 中传递它,也可以像 res.locals.varName = catchedBody 一样使用 res.locals,然后您可以在 app.get 函数中使用它,因为它在整个 http 请求期间都可用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-27
      • 2012-04-11
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 2016-09-23
      相关资源
      最近更新 更多