简体   繁体   中英

Angular application client side caching

The problem

We are using Angular.js for our front-end application that is served from an Express server.

Some of our users are experiencing random issues with the application, but when they clear their browser's cache, the problem is resolved.

We also notice that when we push a new version of our application online, we have to hard refresh before we can see the new changes.

How can we make sure that when we push a new version of the application, that all the users see the new updated version?

Technical details

The express code we use in order to serve the Angular App:

var app = express();

app.use(function(req, res, next) {
    var schema = req.headers["x-forwarded-proto"];

    // --- Do nothing if schema is already https
    if (schema === "https")
        return next();

    // --- Redirect to https
    res.redirect("https://" + req.headers.host + req.url);
});

app.use(function(req, res, next) {
   res.setHeader("Cache-Control", "public, max-age=3600");
   return next();
});

app.use(express.logger('dev'));
app.use(gzippo.staticGzip("" + __dirname + "/dist"));

//prerender is used for SEO
app.use(prerender);
app.use('/', express.static(__dirname + '/'));

//HTML5 mode
app.use(function(request, response, next) {
   response.sendfile(__dirname + '/dist/index.html');
});

app.listen(process.env.PORT || 5000);

As you can see, we use a middleware to set the Cache-Control max-age to 1hour. When we use curl to check the headers we get the following (correct Cache-Control value).

curl命令的屏幕截图

However, when we check the response header in Chrome, the Cache-Control max-age is set to one week.

镀铬头

Also very important, we use Grunt-rev so that every time we deploy the application, the CSS and JS file(s) have a different unique string prepended to their name. (As a result this will also changes the index.html page).

Thank you for your time and help.

Your problem is that you need to handle caching from gzippo!

What is happening in your code is that your custom middleware is going to write Cache-Control header but after gzippo handled the request, it is going to re-write Cache-Control header and set it to 1 week (the default according to the doc ). Your middleware has been "ignored".

What you need to do is

  1. Remove the custom middleware that injects Cache-Control header.
  2. Update gzippo call like the following

     app.use(gzippo.staticGzip("" + __dirname + "/dist", { clientMaxAge: 3600 * 1000 // 1 hour, it seems gzippo takes milliseconds, not seconds })); 

And you're done :)

For other information you can checkout the other options the gzippo documentation

Hope that helps, Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM