我已经读过,为了避免Node.js中的缓存,有必要使用:
res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
但是我不知道如何使用它,因为当我在我的代码中放入这一行时,我会得到错误。
我的函数(我认为我必须对Cache-Control头进行编程)是:
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();
}
});
}
有人知道如何在我的代码中不缓存吗?
发布于 2013-12-07 01:12:10
你已经写好了你的标题。我不认为你可以添加更多之后,所以只需要把你的头放在你的第一个对象中。
res.writeHead(200, {
'Content-Type': mimeType,
'Content-Length': contents.length,
'Accept-Ranges': 'bytes',
'Cache-Control': 'no-cache'
});
发布于 2013-12-07 01:23:23
利用中间件添加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();
}
});
}
如果这对你有效,请告诉我。
发布于 2015-05-26 16:23:07
在您的响应上设置这些标头:
'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()
});
https://stackoverflow.com/questions/20429592
复制相似问题