簡體   English   中英

在javascript中關閉緩存

[英]turn caching off in javascript

大家好,我想通過向請求消息發送的URL的查詢字符串部分添加隨機值來關閉緩存。

我有一台服務器,將etag作為字符串發送到我的客戶端,我想確保沒有緩存在進行setRequestHeaders,但是我還應該添加一個類似於POST /message?x=0.123456789 HTTP /的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();
};*/

錯誤在

因此,您遇到的錯誤與跨域資源共享有關,而跨域資源共享與緩存或查詢字符串無關。 看來您正在嘗試通過file://網址進行AJAX調用,但您無法這樣做。

如果您從Node.js應用程序提供有問題的頁面,則該消息應消失。

如果您無法執行此操作,請設置該應用程序以發送CORS標頭。 您可以在MDN上詳細了解CORS ,但簡短的版本是您需要發送如下所示的標頭(其中otherdomain.com是托管網頁的位置):

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

請注意,您仍然必須通過HTTP提供網頁; 據我所知,您根本無法通過file:// URL加載的頁面執行AJAX。

您可以添加'_=' + new Date().getTime(); 到網址的查詢字符串。 由於尚不清楚網址是否已附加查詢字符串,因此很難給出更完整的答案。 可以是url += '?_=' + new Date().getTime(); url += '&_=' + new Date().getTime();

我將其保留在此處,因為它似乎可以回答OP提出的問題。 但是,OP所遇到問題的解決方案是Adam Brenecki在下面的回答。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM