【发布时间】:2022-12-27 20:11:17
【问题描述】:
According to this
The "max-age" request directive indicates that the client is unwilling to accept a response whose age is greater than the specified number of seconds
So I tried setting up a small app to test it out. I set the
Cache-Control: 'max-age=5'in the request andCache-Control: 'max-age=10'in the response. If I understand the above sentence correctly, every request I make after 5 seconds should receive a brand new response. But after 5 seconds, I still receive the "old response". Am I missing anything?
Here are code:
Client:<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button onclick="onClick()"> Fetch </button> <div class="response-container"> </div> <script> const onClick = async () => { const response = await fetch('http://localhost:3000/hello', { headers: { 'Cache-Control': 'max-age=5' } }); const result = await response.json(); console.log('result', result) // create a div and append to div with class .response-container const div = document.createElement('div'); div.innerHTML = result.message; document.querySelector('.response-container').appendChild(div); } </script> </body> </html>
Server:var express = require("express"); var app = express(); const cors = require("cors"); app.use(cors()); let requestIdx = 1; app.get("/hello", function (req, res) { // set cache control headers to expire in 10 seconds res.setHeader("Cache-Control", "max-age=10"); res.send({ message: "Hello World" + requestIdx++, }); }); app.listen(3000, function () { console.log("Server started on port 3000"); });
【问题讨论】:
-
Where is the "old response" coming from? I don't see any caching mechanism in your server code.
-
Although it occurs to me that you may be trying to bypass the browser caching. If that is the case, I doubt it will work. It looks like the max-age is supposed to be enforced by the server.
-
@StephenOstermiller I set the Cache-Control to the response header. It will specify that the request to /hello should return the cache response which has an age is less than 10 seconds.
-
@StephenOstermiller if it's the case I doubt the example from the link I attached at the beginning of my question. I think that setting the cache-control in the request header should have a higher priority than in the response. I tried setting max-age=0 and it worked but any value greater than 0 seems to have no effect
-
Your interpretation of RFC 7234 looks correct to me, the issue here is probably just that browser caches are weird and aren't necessarily fully compliant. If it's a browser cache issue, it would interesting to try your code in all the major browsers to see if there is any difference in behavior.
标签: http web caching http-headers