首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Node.js服务器中没有缓存

Node.js服务器中没有缓存
EN

Stack Overflow用户
提问于 2013-12-07 01:06:30
回答 5查看 77.5K关注 0票数 47

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

代码语言:javascript
复制
res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');

但是我不知道如何使用它,因为当我在我的代码中放入这一行时,我会得到错误。

我的函数(我认为我必须对Cache-Control头进行编程)是:

代码语言:javascript
复制
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();
    }
  });
}

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

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2013-12-07 01:12:10

你已经写好了你的标题。我不认为你可以添加更多之后,所以只需要把你的头放在你的第一个对象中。

代码语言:javascript
复制
res.writeHead(200, {
  'Content-Type': mimeType,
  'Content-Length': contents.length,
  'Accept-Ranges': 'bytes',
  'Cache-Control': 'no-cache'
});
票数 32
EN

Stack Overflow用户

发布于 2013-12-07 01:23:23

利用中间件添加no-cache标头。在您想要关闭缓存的任何地方都可以使用这个中间件。

代码语言:javascript
复制
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();
}

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

代码语言:javascript
复制
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();
    }
  });
}

如果这对你有效,请告诉我。

票数 146
EN

Stack Overflow用户

发布于 2015-05-26 16:23:07

在您的响应上设置这些标头:

代码语言:javascript
复制
'Cache-Control': 'private, no-cache, no-store, must-revalidate'
'Expires': '-1'
'Pragma': 'no-cache'

如果您使用express,则可以添加此中间件以使所有请求都没有缓存:

代码语言:javascript
复制
// var app = express()
app.use(function (req, res, next) {
    res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    res.header('Expires', '-1');
    res.header('Pragma', 'no-cache');
    next()
});
票数 53
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20429592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档