浏览器缓存:Json 响应

Browser cache: Json response

我尝试使用 Etag 缓存来自 api 请求的 json 响应。 我这样调用 http://localhost:3000/api/config 并得到:

响应Headers:
Cache-Control:public, max-age=31557600
Connection:keep-活着
Content-Length:11
Content-Type:application/json;字符集=utf-8
Date:Wed,2015 年 5 月 13 日 11:41:52 格林威治标准时间
ETag:“94d52736bcd99b1ac771f13b1bbdf622”
X-Powered-By:快递

回复:{id: 1}

我希望浏览器缓存响应并在 "f5" 之前发送带有下一个请求触发的 Etag。但事实并非如此。

请求Headers第二个请求:
接受:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q= 0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:no-cache
Connection:keep-活着
Host:localhost:3000
Pragma:no-缓存
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 [=65= .36

那么不可能缓存纯 json 响应,通过直接 api 请求获得?
或者我错过了什么。

api 是用 express 完成的节点 js 测试实现:

router.get('/config', function(req, res) {
    var eTag = crypto.createHash('md5').update(JSON.stringify(config)).digest('hex');
    res.setHeader('ETag', '"' + eTag + '"');
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Cache-Control', 'public, max-age=31557600');
});

使用 chrom(42.x) 和 firefox(37.x) 进行测试

感谢回复。

看起来您可能正在使用 chrome。 Chrome 应在 "f5" 之后的请求中包含以下 header:

If-None-Match:"94d52736bcd99b1ac771f13b1bbdf622"

如果您没有看到这个,请检查 chrome 设置/常规并确保 选中“禁用缓存(当 DevTools 打开时)”:

使用 jQuery 我们可以使用 ifModified 选项:

$.ajax({
   type: "GET",
   ifModified: true,
   url: "http://localhost:3000/api/config"
}).then(function(data) {
   . . .
});

嗨,这段代码似乎对我有用:

router.get('/config', function(req, res) {
    var eTag = crypto.createHash('md5').update(JSON.stringify(config)).digest('hex');

    if (req.headers['if-none-match'] && req.headers['if-none-match'] === '"' + eTag + '"') {
        res.status(304);
        res.end();
    } else {
        res.setHeader('ETag', '"' + eTag + '"');
        res.setHeader('Content-Type', 'application/json');
        res.setHeader('Cache-Control', 'public, max-age=31557600');
        res.send(JSON.stringify(config));
    }
});

使用浏览器 url 调用 api 栏 http://localhost:3000/api/config