【问题标题】:turn caching off in javascript在javascript中关闭缓存
【发布时间】:2014-03-25 11:04:41
【问题描述】:

大家好,我正在尝试通过以下方式关闭缓存 向随请求消息一起发送的 URL 的查询字符串组件添加随机值。

我有一个服务器将 etag 作为字符串发送给我的客户端,我想确保没有缓存正在进行我已经 setRequestHeaders 但我还应该添加一个类似于 POST /message?x= 的 http 请求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();
};*/

错误在

【问题讨论】:

  • 那么你的问题是什么?
  • 如何使用 math.random() 添加随机值
  • 您说它会抛出错误,但您没有向我们提供这些错误。如果您给我们一些日志输出或控制台输出,以便我们可以在您使用 math.random() 函数时看到它们是什么,这将有所帮助。
  • 您使用什么 url 来访问发出此请求的页面?对我来说似乎是一个跨域问题。
  • 我添加了错误我应该添加我的服务器端js代码吗?

标签: javascript node.js caching


【解决方案1】:

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

如果您从 Node.js 应用程序提供相关页面,该消息应该会消失。

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

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

请注意,您仍然必须通过 HTTP 提供页面;据我所知,您根本无法从通过file:// URL 加载的页面执行 AJAX。

【讨论】:

  • 好吧,如果我拿走 math.random 并只使用 makeRequest('localhost:5000') 它会正确提醒 httpRequest.responsetext 这不是 ajax 请求吗?
  • 我将如何“从您的 Node.js 应用程序提供相关页面”
  • @RyanWilliams 好的,这很有趣。如果您将'http://localhost:5000' 更改为'http://localhost:5000/'(注意尾部斜杠)会怎样?
  • 如果我注释掉 httpRequest.setRequestHeader("pragma", "no-cache"); httpRequest.setRequestHeader("Cache-Control", "no-cache", "no-store"); ajax 按钮将正确显示带有 alert(etagstring) 的 etag 有没有办法从 http:/localhost/ 而不是 file:/ 运行我的文件而不使用 wamp 只使用 node.js 和代码?
  • 你需要将你的Content-Type设置为text/html,否则Chrome会认为这是一个纯文本文件。
【解决方案2】:

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

我将把这个答案留在这里,因为它似乎回答了 OP 提出的问题。但是 OP 遇到的问题的解决方案是 Adam Brenecki 在下面的回答。

【讨论】:

  • 这是否进入 httpRequest.open(POST, 'url_=' + stuff, true);我听说我必须使用 POST
  • 如果你要使用 POST,你应该使用 POST,或者 GET 代表 GET。我正在尝试从您提供的样本中拼凑起来,我最好的选择是您的问题。看起来您要问的关键是如何防止响应缓存,不是吗?
  • @RyanWilliams 您不必使用 POST。 GET 也可以正常工作。这完全取决于您对您使用 POST 还是 GET 的要求。
  • @JonTaylor ...但如果你想发布,你确实需要使用 POST,不是吗?要进行 POST(如果这是真正需要的),OP 可以看这里:stackoverflow.com/questions/9713058/…
  • @jameslafferty 是的,当然,我的意思是他的问题似乎是关于防止缓存,这与 GET 或 POST 无关。他会得到我们两者相同的行为。
猜你喜欢
  • 2017-04-17
  • 2014-02-10
  • 1970-01-01
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 2012-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多