在nodejs服务器中没有caching

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

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

但是我不知道如何使用它,因为当我把这行代码放到代码中的时候会出错。

我的function(我认为我不得不编程caching)是:

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

有谁知道如何把没有caching在我的代码? 谢谢

你已经写好了你的头文件。 我不认为你可以添加更多,所以只要把你的头在你的第一个对象。

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

利用中间件添加no-cache标头。 使用这个中间件,你打算closurescaching。

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

让我知道这是否适合你。

设置您的响应这些标头:

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

如果你使用express,你可以添加这个中间件在所有的请求上都没有caching:

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

Pylinux的答案为我工作,但经过进一步检查,我发现了快递头盔模块,为您处理一些其他安全function。

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

要使用,在express.js中安装并需要头盔,然后调用app.use(helmet.noCache());

在通过快速和新鲜模块的源代码进行深入探讨之后,这是从服务器端(在调用res.end之前)工作的:

 req.headers['if-modified-since'] = undefined; req.headers['if-none-match'] = undefined; 

讨厌,但它的作品。