我已经读过,为了避免在 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/