压缩 (gzip) 在 NestJS 中不起作用

问题描述 投票:0回答:3

使用命令创建了一个标准的 NestJS 项目:

nest new project-name
。之后,我安装了压缩
npm i --save compression
并将其插入项目中。

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as compression from 'compression';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(compression());
  await app.listen(3000);
}
bootstrap();

但是压缩不起作用,响应没有

gzip

Response in browser

我已经尝试过清除缓存、重新启动浏览器,但没有任何效果。

感谢您的帮助

compression nestjs
3个回答
3
投票

首先,安装以下软件包:

npm i --save compression

main.ts
文件中的bootstrap function中,应用压缩中间件,如下

async function bootstrap() {
  const app: INestApplication = await NestFactory.create(AppModule);
  ...
  app.use(compression({
    filter: () => { return true },
    threshold: 0
  }));

  ...
  await app.listen(4100);
}

然后你就会看到结果了

注意

如果您的浏览器已打开,请先将其关闭,然后再次打开

Control+Shift+RShift + F5 = 重新加载当前页面,忽略缓存内容。


0
投票

如果其他方法都不起作用:

  const expressApp = express();
  expressApp.use(compression());
  const expressAdapter = new ExpressAdapter(expressApp);
  const app = await NestFactory.create(AppModule, expressAdapter);
  await app.listen(3000);

0
投票

你还应该有“Cache-Control”标头

例如:

@Header('Cache-Control', 'public,max-age=31536000')

因为有一个检查: [1]:https://i.stack.imgur.com/GfjCl.png

© www.soinside.com 2019 - 2024. All rights reserved.