2014-02-24 74 views
1

大家好,我試圖通過 將緩存關閉向隨請求消息一起發送的URL的查詢字符串組件添加一個隨機值。在javascript中關閉緩存

我有一個服務器發送etag作爲字符串到我的客戶端,我想確保沒有緩存正在進行我已setRequestHeaders但我也應該添加一個HTTP請求類似於POST /消息?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> 

編輯使用的node.js我運行使用main.js服務器添加錯誤

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. 

其是

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(); 
};*/ 

的誤差在

+0

那麼你的問題是什麼? –

+0

如何添加隨機使用math.random() –

+0

添加隨機值你說它是拋出錯誤,但你沒有提供給我們這些錯誤。如果你給我們一些日誌輸出或控制檯輸出,所以當你使用math.random()函數時,這會有所幫助。 –

回答

3

所以,你得到的錯誤是與跨源資源共享有關,它與緩存或查詢字符串無關。它看起來像你試圖從file:// url進行AJAX調用,你不能這樣做。

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

如果您不能這樣做,請設置該應用程序以發送CORS標頭。你可以read about CORS in detail at MDN,但短期的版本是,你需要發送一個報頭,看起來像這樣(其中otherdomain.com是Web網頁託管):

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

注意,你仍然必須服務於頁面通過HTTP;據我所知,您無法從通過file:// URL加載的頁面進行AJAX操作。

+0

以及如果我拿走math.random並且只使用makeRequest('http:// localhost:5000')它會正確警告httpRequest.responsetext是不是一個ajax請求? –

+0

我將如何「從你的Node.js應用程序服務頁面」 –

+0

@RyanWilliams好的,這很有趣。如果你改變''http:// localhost:5000',那麼它會說''http:// localhost:5000 /''(注意最後一個斜線)會發生什麼? –

2

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

我會在這裏留下這個答案,因爲它似乎回答OP所問的問題。但是,OP正在經歷的問題的解決方案是Adam Brenecki的答案如下。

+0

這是否在httpRequest.open中(POST,'url_ ='+ stuff,true);我聽說我不得不使用POST –

+0

如果你打算進入POST,你應該使用POST,或GET GET。我試圖從你提供的樣本中把它拼湊在一起,並且對你的問題我是最好的選擇。它看起來像你問的關鍵是如何防止響應的緩存,不是嗎? – jameslafferty

+0

@RyanWilliams您不必使用POST。 GET也能正常工作。這完全取決於你的要求是否使用POST或GET。 –