我已经读过为了避免在nodejs中缓存,有必要使用:
"res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');"
Run Code Online (Sandbox Code Playgroud)
但是我不知道如何使用它,因为当我在代码中放入该行时会出现错误.
我的功能(我认为我必须编程没有缓存)是:
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();
}
});
}
Run Code Online (Sandbox Code Playgroud)
有谁知道如何在我的代码中没有缓存?谢谢
vmx*_*vmx 137
利用中间件添加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();
}
Run Code Online (Sandbox Code Playgroud)
在路由定义中使用中间件:
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();
}
});
}
Run Code Online (Sandbox Code Playgroud)
如果这对您有用,请告诉我.
Pyl*_*nux 47
在响应中设置这些标头:
'Cache-Control': 'private, no-cache, no-store, must-revalidate'
'Expires': '-1'
'Pragma': 'no-cache'
Run Code Online (Sandbox Code Playgroud)
如果使用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()
});
Run Code Online (Sandbox Code Playgroud)
Bra*_*rad 29
你已经写好了你的标题.我不认为你可以在完成后添加更多内容,所以只需将标题放在第一个对象中即可.
res.writeHead(200, {
'Content-Type': mimeType,
'Content-Length': contents.length,
'Accept-Ranges': 'bytes',
'Cache-Control': 'no-cache'
});
Run Code Online (Sandbox Code Playgroud)
您可以使用nocache中间件来关闭缓存.
npm install --save nocache
Run Code Online (Sandbox Code Playgroud)
将中间件应用到您的应用程序
const nocache = require('nocache');
...
app.use(nocache());
Run Code Online (Sandbox Code Playgroud)
这会禁用浏览器缓存.
归档时间: |
|
查看次数: |
64685 次 |
最近记录: |