在javascript中关闭缓存

时间:2014-02-24 00:21:25

标签: javascript node.js caching

大家好我试图将缓存关闭 将随机值添加到随请求消息一起发送的URL的查询字符串组件中。

我有一个服务器将etag作为字符串发送到我的客户端,我想确保没有缓存,我已经setRequestHeaders但我也应该添加一个类似于POST /消息的http请求?x = 0.123456789 HTTP / 1.1

这是我的客户代码

<html>
<header><title>This is title</title></header>
<body>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
  Make a request
</span>
<script type="text/javascript">
(function() {
  var httpRequest;
  var x= Math.random();
  document.getElementById("ajaxButton").onclick = function() { makeRequest('http://localhost:5000/'); };
  function makeRequest(url) {
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
      try {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } 
      catch (e) {
        try {
          httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) {}
      }
    }
    if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }
    httpRequest.onreadystatechange = alertContents;
    httpRequest.open('GET', url, true);
    //httpRequest.setRequestHeader("pragma", "no-cache");
    //httpRequest.setRequestHeader("Cache-Control", "no-cache", "no-store"); 
    httpRequest.send();

  }
  function alertContents() {
    if (httpRequest.readyState === 4) {
      if (httpRequest.status === 200) {
        var etagString = httpRequest.responseText;
        alert(etagString);
      } else {
        alert('There was a problem with the request.');
      }
    }
  }
})();
</script>
</body>
</html>

编辑添加错误

XMLHttpRequest cannot load http://localhost:5000/?_0.1909303846769035. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

使用node.js我使用main.js运行服务器,这是

var http = require('http');
var domain = require('domain');
var root = require('./root'); // do I have to replace root w/ message 
var image = require('./image');  // for better readability?


function replyError(res) {
  try {
    res.writeHead(500);
    res.end('Server error.');
  } catch (err) {
    console.error('Error sending response with code 500.');
  }
};

function replyNotFound(res) {
  res.writeHead(404);
  res.end('not found');
}

function handleRequest(req, res) {
  console.log('Handling request for ' + req.url);
  if (req.url === '/') {
    root.handle(req, res);
  }
  if (req.url === '/image.png'){
    image.handle(req, res);
  } 
  else {
    replyNotFound(res);
  }
}



var server = http.createServer();

server.on('request', function(req, res) {
  var d = domain.create();
  d.on('error', function(err) {
    console.error(req.url, err.message);
    replyError(res);
  });
  d.run(function() { handleRequest(req, res)});
});

function listen(){
server.listen(5000);
}

root.init(listen);

和root.js里面是

var http = require('http');
var response = require('./response');
var body;
var etag;



exports.handle = function(req, res) {
  if (req.headers['if-none-match'] === etag) {
    console.log('returning 304');
    return response.replyNotModified(res);
  } 
  res.writeHead(200, {'Content-Type': 'text/plain',
  'Content-Length': body.length,
  "Access-Control-Allow-Origin":"*",
  "Access-Control-Allow-Headers":"X-Requested-With",
  'ETag' : etag
  }); 
  res.end(body);   
}


exports.init = function(cb) {
  require('fs').readFile('app.html', function(err, data) {
    if (err) throw err;
    etag = response.generateETag(data); //
    body = etag;
    console.log("init");
    cb();
  });
}

/*function generateETag(buffer) {   
  var shasum = require('crypto').createHash('sha1');
  shasum.update(buffer, 'binary'); 
  return shasum.digest('hex');    
  console.log(shasum.digest('hex'));
}
var replyNotModified = function(res) {
  res.writeHead(304);
  res.end();
};*/

错误在

2 个答案:

答案 0 :(得分:3)

因此,您获得的错误与跨源资源共享有关,这与缓存或查询字符串无关。您似乎正在尝试从file://网址进行AJAX调用,这是您无法做到的。

如果您从Node.js应用程序提供有问题的页面,该消息应该消失。

如果您不能这样做,请将该应用设置为发送CORS标头。您可以read about CORS in detail at MDN,但简短版本是您需要发送一个类似于此的标头(其中otherdomain.com是托管网页的位置):

Access-Control-Allow-Origin: http://otherdomain.com

请注意,您仍然需要通过HTTP提供页面;据我所知,你不能通过file://网址加载的页面完成AJAX。

答案 1 :(得分:2)

您可以将'_=' + new Date().getTime();添加到网址的查询字符串中。由于不清楚网址是否已经附加了查询字符串,因此很难给出更完整的答案。它可以是url += '?_=' + new Date().getTime();url += '&_=' + new Date().getTime();

我会在这里留下这个答案,因为它似乎回答了OP所要求的问题。但OP正在经历的问题的解决方案是Adam Brenecki的回答。