简体   繁体   English

在javascript中关闭缓存

[英]turn caching off in javascript

Hi all I am trying to turn caching off by Adding a random value to the query string component of the URL sent with the request message. 大家好,我想通过向请求消息发送的URL的查询字符串部分添加随机值来关闭缓存。

I have a server that sends the etag as a string to my client and I want to make sure no caching is going on I already setRequestHeaders but i'm also supposed to add an http request similar to POST /message?x=0.123456789 HTTP/1.1 我有一台服务器,将etag作为字符串发送到我的客户端,我想确保没有缓存在进行setRequestHeaders,但是我还应该添加一个类似于POST /message?x=0.123456789 HTTP /的http请求。 1.1

this is my client code 这是我的客户代码

<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>

edit for adding errors 编辑添加错误

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. 

using node.js I run the server using main.js which is 使用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);

and inside root.js is 在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();
};*/

the errors are in 错误在

So, the error that you're getting is to do with cross-origin resource sharing, which has nothing to do with caching or query strings. 因此,您遇到的错误与跨域资源共享有关,而跨域资源共享与缓存或查询字符串无关。 It looks like you're trying to make AJAX calls from a file:// url, which you can't do. 看来您正在尝试通过file://网址进行AJAX调用,但您无法这样做。

If you serve the page in question from your Node.js app, that message should go away. 如果您从Node.js应用程序提供有问题的页面,则该消息应消失。

If you can't do that, set up that app to send CORS headers. 如果您无法执行此操作,请设置该应用程序以发送CORS标头。 You can read about CORS in detail at MDN , but the short version is that you need to send a header that looks like this (where otherdomain.com is where the Web page is hosted): 您可以在MDN上详细了解CORS ,但简短的版本是您需要发送如下所示的标头(其中otherdomain.com是托管网页的位置):

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

Note that you'll still have to serve the page over HTTP; 请注意,您仍然必须通过HTTP提供网页; to my knowledge you can't do AJAX at all from a page loaded via a file:// URL. 据我所知,您根本无法通过file:// URL加载的页面执行AJAX。

You could add '_=' + new Date().getTime(); 您可以添加'_=' + new Date().getTime(); to the query string of the url. 到网址的查询字符串。 Since it isn't clear whether the url already has a query string attached to it, it's hard to give a more complete answer. 由于尚不清楚网址是否已附加查询字符串,因此很难给出更完整的答案。 It'd be either url += '?_=' + new Date().getTime(); 可以是url += '?_=' + new Date().getTime(); or url += '&_=' + new Date().getTime(); url += '&_=' + new Date().getTime(); .

I'll leave this answer here because it seems to answer the question that the OP was asking. 我将其保留在此处,因为它似乎可以回答OP提出的问题。 But the solution to the problem the OP was experiencing is Adam Brenecki's answer below. 但是,OP所遇到问题的解决方案是Adam Brenecki在下面的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM