【问题标题】:How to enable gzip on my node server using connect?如何使用连接在我的节点服务器上启用 gzip?
【发布时间】:2020-04-24 03:13:25
【问题描述】:

我正在尝试让我的节点服务器 gzip 它给出的响应。我有以下内容:


const connect = require('connect');
const formDataRequests = ['communities/upsert'];
const app = connect();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
...

我做了一些研究(例如 https://alligator.io/nodejs/compression/ ),但这需要和 express 应用程序。有谁知道我可以导入/等什么模块来得到这个来 gzip 响应?

【问题讨论】:

  • 您至少尝试过吗? expressJs 也基于http 服务器,并且您使用的库还支持与 expressJs 中间件完全一样编写的中间件...尝试使用简单的路线,检查数据大小有无此...和看看有没有用???顺便说一句,您无需包含bodyParser,只需将其替换为express 变量即可,例如app.use(express.json()),因为express 现在包含bodyParser 库????
  • 嗨@balexandre,你的意思是app.use(compression())

标签: node.js gzip connect


【解决方案1】:

根据connect docs,可以使用相同的压缩中间件:

const compression = require('compression');
app.use(compression());

【讨论】:

  • 这个中间件不适合我。我已经尝试了所有有助于压缩但仍然无法正常工作的参数。
  • @HardikPatel 您使用的是连接中间件还是 express 中间件?你如何测试它是否有效?
  • 我正在使用快递。压缩是否与express有任何问题。我在另一个具有相同配置的系统中做了同样的事情,它正在工作。为什么会这样?我的主系统仍然面临问题。
【解决方案2】:

使用压缩中间件

const compression = require('compression');
app.use(compression());

为了服务,节点gzip压缩文件使用

app.get('*.js', function (req, res, next) {
    req.url = req.url + '.gz';
    res.set('Content-Encoding', 'gzip');
    res.set('Content-Type', 'text/javascript');
    // console.log('sent')
    next();
});
app.get('*.css', function (req, res, next) {
    req.url = req.url + '.gz';
    res.set('Content-Encoding', 'gzip');
    res.set('Content-Type', 'text/css');
    next();
});

【讨论】:

    【解决方案3】:

    谢谢@jcragun。我们能够让它工作:

    const compression = require('compression');
    app.use(compression());
    

    【讨论】:

      猜你喜欢
      • 2020-09-15
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 2020-08-27
      • 2021-09-23
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多