在JavaScript中closurescaching

大家好,我正试图通过添加一个随机值的请求消息发送的URL的查询string组件来closurescaching。

我有一个服务器发送etag作为string到我的客户端,我想确保没有caching正在进行我已经setRequestHeaders但我也应该添加一个HTTP请求类似于POST /message?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(); };*/ 

错误在

所以,你得到的错误是与跨源资源共享,这与caching或查询string无关。 它看起来像你试图从一个file:// url的AJAX调用,你不能这样做。

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

如果你不能这样做,请设置该应用程序发送CORS标题。 您可以在MDN上详细阅读CORS ,但简短的版本是您需要发送一个如下所示的标头(其中otherdomain.com是网页的托pipe位置):

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

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

你可以添加'_=' + new Date().getTime(); 到url的查询string。 由于目前还不清楚url是否已经附加了查询string,所以很难给出更完整的答案。 它可能是url += '?_=' + new Date().getTime(); 或者url += '&_=' + new Date().getTime();

我会在这里留下这个答案,因为它似乎回答了OP所问的问题。 但是OP所遇到的问题的解决scheme是Adam Brenecki的答案如下。