node.js - Node.js 服务器中没有缓存

标签 node.js caching

我已经读过,为了避免在 Node.js 中缓存,有必要使用:

res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');

但我不知道如何使用它,因为当我将该行放入代码时出现错误。

我的功能(我认为我必须对 Cache-Control header 进行编程)是:

function getFile(localPath, mimeType, res) {
  fs.readFile(localPath, function(err, contents) {
    if (!err) {
      res.writeHead(200, {
        "Content-Type": mimeType,
        "Content-Length": contents.length,
        "Accept-Ranges": "bytes",
      });
      // res.header('Cache-Control', 'no-cache');
      res.end(contents);
    } else {
      res.writeHead(500);
      res.end();
    }
  });
}

有人知道如何在我的代码中放置缓存吗?

最佳答案

利用中间件添加 no-cache header 。在您打算关闭缓存的任何地方使用此中间件。

function nocache(req, res, next) {
  res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
  res.header('Expires', '-1');
  res.header('Pragma', 'no-cache');
  next();
}

在路由定义中使用中间件:

app.get('/getfile', nocache, sendContent);

function sendContent(req, res) {
  var localPath = 'some-file';
  var mimeType = '';
  fs.readFile(localPath, 'utf8', function (err, contents) {
    if (!err && contents) {
      res.header('Content-Type', mimeType);
      res.header('Content-Length', contents.length);
      res.end(contents);
    } else {
      res.writeHead(500);
      res.end();
    }
  });
}

让我知道这是否适合你。

关于node.js - Node.js 服务器中没有缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20429592/

相关文章:

node.js - 登录后如何连接到socket - JWT

node.js - Docker容器没有TMPDIR环境变量

java - 使用 websphere api 获取当前应用程序实例?

java - 为什么 JVM 不缓存 JIT 编译的代码?

qt - QWebkit QWebSettings缓存和QNetworkManager QNetworkDiskCache有什么区别?

node.js - 拒绝访问异常 : User is not authorized to perform dynamodb BatchWriteItem on resource: table

javascript - Nodejs如何在没有setTimeouts的情况下访问外部回调结果?

node.js - 为什么在安装 npm now 包时出现此错误?

python - 在内存中缓存 MySQLdb 数据库查询的结果

c# - OutputCache 属性不适用于 .NET 7 API 端点