Express Compress 在 Node 网站上不工作

Express Compress not working in Node website

我的网站建立在 node + express 上,并尝试使用 this 教程启用 gzip 压缩,但它没有像教程中所示那样工作。我看不到 Content-Encoding 响应 header。

这是我的代码。

const compression = require('compression');
const express = require("express");
const path = require("path");
var redirects = require('express-seo-redirects');
var proxy = require('express-http-proxy');
require('dotenv').config()
/**
 * App Variables
*/
const app = express();
app.use(compression({ filter: shouldCompress, threshold: 0 }));
//app.use(compression()) - //I've also tried this.
function shouldCompress (req, res) {
  if (req.headers['x-no-compression']) {
    // don't compress responses with this request header
   return false
  }

  // fallback to standard filter function
  return compression.filter(req, res)
}
let setCache = function (req, res, next) {
  // here you can define period in second, this one is 1 day
  const period = 1 * 24 * 60 * 60 * 1000 

  // you only want to cache for GET requests
  if (req.method == 'GET') {
    res.set('Cache-control', `public, max-age=${period}`)
  } else {
    // for the other requests set strict no caching parameters
    res.set('Cache-control', `no-store`)
  }
  // res.set('Content-Encoding', 'gzip')
  // remember to call next() to pass on the request
  next()
}
app.use(setCache)

当我在 app.get("/", (req, res) => { 中使用 res.set('Content-Encoding', 'gzip') 时,它显示响应 header 但网站停止工作(除空白屏幕外未显示任何错误)。

下面的图片是我的休息代码。

Gzip 压缩仅针对资源文件(css、js 等)显示。所以我通过在 setCache 函数中添加 res.contentType('text/html'); 来解决它。

const exceptions = ['.js', '.css', '.ico', '.jpg', '.jpeg', '.png', '.gif', '.tiff', '.tif', '.bmp', '.svg', '.ttf', '.eot', '.woff', '.php', '.xml', '.xsl'];
let setCache = function (req, res, next) {
  // here you can define period in second, this one is 5 minutes
  const period = 1 * 24 * 60 * 60 * 1000;
  if(!exceptions.some(v => req.url.includes(v))){
    res.contentType('text/html');
  }
  // you only want to cache for GET requests
  if (req.method == 'GET') {
    res.set('Cache-control', `public, max-age=${period}`)
  } else {
    // for the other requests set strict no caching parameters
    res.set('Cache-control', `no-store`)
  }
  // res.set('Content-Encoding', 'gzip')
  // remember to call next() to pass on the request
  next()
}
app.use(setCache)