nodejs服务器中没有缓存

时间:2013-12-06 17:06:30

标签: node.js caching

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

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

但是我不知道如何使用它,因为当我在代码中添加该行时会出现错误。

我的功能(我认为我必须编程没有缓存)是:

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

}

有谁知道如何在我的代码中放置缓存?感谢

6 个答案:

答案 0 :(得分:131)

使用中间件添加no-cache标头。使用此中间件 - 您打算关闭缓存。

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

请告诉我这是否适合您。

答案 1 :(得分:42)

在回复中设置这些标题:

'Cache-Control': 'private, no-cache, no-store, must-revalidate'
'Expires': '-1'
'Pragma': 'no-cache'

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

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

答案 2 :(得分:26)

您已经编写过标题了。我不认为你在完成之后可以添加更多内容,所以只需将标题放在第一个对象中即可。

res.writeHead(200, {
  'Content-Type': mimeType,
  'Content-Length': contents.length,
  'Accept-Ranges': 'bytes',
  'Cache-Control': 'no-cache'
});

答案 3 :(得分:6)

您可以使用 nocache 中间件来关闭缓存。

npm install --save nocache

将中间件应用于您的应用

const nocache = require('nocache');
...
app.use(nocache());

这将禁用浏览器缓存。

答案 4 :(得分:1)

Pylinux的回答对我有用,但经过进一步检查,我发现了面向快递的头盔模块,为您处理其他一些安全功能。

http://webapplog.com/express-js-security-tips/

要在express.js中使用,安装和要求头盔,请致电SELECT a.fname, b.lname, a.empid FROM yourTable AS a INNER JOIN yourTable AS b ON a.empid = b.empid AND a.fname IS NOT NULL AND b.lname IS NOT NULL

答案 5 :(得分:0)

在深入了解快速和新模块的源代码之后,这可以从服务器端进行(在调用res.end之前):

Derived

令人讨厌,但它确实有效。