문제

I am creating a dynamic node.js website. I don't want the browser to store the page, i.e whenever the user clicks reload I want the page to reload from scratch. At the moment my page still appears to be cached even though I am sending "Cache-Control":"no store". Here is my server:

// requires node's http module
var http=require('http');
var url=require('url');
var fs=require('fs');
// creates a new httpServer instance
http.createServer(function (req, res) {
// this is the callback, or request handler for the httpServer
log('in server callback')
res.ins=res.write;

var parse=url.parse(req.url,true);
var path0=parse.pathname;
var mime=core.getMime(path0)
console.log(path0)
// respond to the browser, write some headers so the 
// browser knows what type of content we are sending

var servePage=function(){
    var path='./page'+path0+'.js'
    console.log(path)
    fs.exists(path,function(e){
        if(e){
            log('serving page')
            var exp=require(path); 
            if(exp && exp.html){
                var html=exp.html
            }
            else{
                var html='bad file'
            }
        }
        else{
            console.log('no page to serve')
            var exp=require('./page/pageHome.js')
            var html=exp.html
        }
        res.writeHead(200, {'Content-Type': mime, 'Cache-Control': 'no store'});
        res.ins(html);
        res.end();
    })
}
servePage()
}).listen(8080); // the server will listen on port 8080

I also tried creating a self link with a random query string such as 'http://mydomain.com/page?q=42' but this still did not bypass the cache. What am I doing wrong? Thanks!

도움이 되었습니까?

해결책

You are doing it generally wrong.

Please read require. It is used to load modules for node.js and execute it. Not for actually serving files for requests via http.
require will always cache execution results and will keep reference of module, and you have to clear it manually - but as mentioned above this is not your case.

Please read this great post: Nodejs send file in response that describes how to send files via node.js.

You can set no-cache header for it as well, but it is a 'bad way' of doing things. You might better not touch any headers at all, and do extra query on front-end, but even not always.

res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top