Nodejs Express 框架缓存 [英] Nodejs Express framework caching

查看:57
本文介绍了Nodejs Express 框架缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Nodejs 和 Express Js.此外,我将 NowJS 添加到 Express Js 以执行一些实时操作.

I am using Nodejs and Express Js. Also I add NowJS to the Express Js to do some real-time stuffs.

在我的配置文件中

app.configure('production', function() {
var oneYear = 31557600000;
app.use(express.static(__dirname + '/public', { maxAge: oneYear }));
app.use(express.errorHandler());});

我使用以下命令运行应用程序:

And I run the application using this command:

$ NODE_ENV=production node app.js

然而,文件(图像、css、js)似乎没有被缓存,它们总是作为新文件提供.

However, the files(images, css, js) seem not to be cached, they are always served as new file.

P/s:我刚刚用本地主机测试过,缓存似乎可以在本地主机上工作,但是,当上传到服务器时,缓存不再工作了.

P/s: I have just tested it with localhost, the cache seems to work on localhost, however, when uploading to the server, the cache is not working anymore.

推荐答案

Express 建立在 Connect 之上,Connect 提供静态"中间件.这是缓存的底层代码:

Express is built on Connect, and Connect provides the "static" middleware. Here's the code under the hood for the caching:

if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + (maxAge / 1000));

您可以在此处找到该代码:

You can find that code here:

https://github.com/senchalabs/连接/blob/master/lib/middleware/static.js#L147

如您所见,Express 正在向浏览器发送Cache-Control"标头,告诉浏览器将该文件缓存一段时间.因此,这不是加载一次文件,然后始终将其提供给所有客户端",而是告诉每个客户端在第一次下载文件时缓存文件"(这意味着所有客户端都必须下载该文件在为他们缓存之前一次).

So as you can see Express is sending a "Cache-Control" header to the browser, telling him to cache that file for a period. So this isn't a "load a file once and then always serve it to all clients", but more of a "tell each client to cache the file the first time he downloads it" (which means all the clients will have to download that file once before it's cached for them).

这篇关于Nodejs Express 框架缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆