简体   繁体   English

在Express JS 4.4.1中压缩文件(gzip)

[英]Compressing files (gzip) in express js 4.4.1

I' using express js app as a web server but all static content is unzipped (js and css files). 我将express js应用程序用作Web服务器,但所有静态内容均已解压缩(js和css文件)。 I tried a couple of solutions like using compression https://github.com/expressjs/compression but can't get is working. 我尝试了几种解决方案,例如使用压缩https://github.com/expressjs/compression,但无法正常工作。 Here is the way I'm doing it (only the part relevant for compression usage): 这是我的操作方式(仅与压缩使用有关的部分):

var app = module.exports = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(morgan('dev'));

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());

var cacheTime = 86;     // 7 days
app.use(compression());
app.use(express.static(__dirname + '/public',{ maxAge: cacheTime }));

http.createServer(app).listen(app.get('port'), function () {
    console.log('Express server listening on port ' + app.get('port'));
});

Express middleware is always processed in order of declaration. Express中间件始终按声明顺序进行处理。

You have this: 你有这个:

app.use(express.static(...));
app.use(compression());

That means that a request is first processed by express.static() , and when it can handle such a request, it will generate a response immediately and the request will never be passed to the compression middleware. 这意味着请求首先express.static() ,并且当它可以处理此类请求时,它将立即生成响应,并且该请求将永远不会传递到压缩中间件。

If you swap the order of the middleware, like this: 如果交换中间件的顺序,如下所示:

app.use(compression());
app.use(express.static(...));

All requests will first pass through the compression middleware, which will set up things so responses will get compressed. 所有请求都将首先通过压缩中间件,该中间件将进行设置,以便响应得到压缩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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