快递不提供压缩的资产

时间:2018-07-24 19:20:23

标签: javascript express gzip

我有一个快速应用程序,它托管一个JS应用程序,html页面和捆绑的样式。

我正在将CSP应用于我的Express应用程序,但是它现在不提供任何压缩的资产,我不知为什么。

快递

const express = require('express');
const expressStaticGzip = require('express-static-gzip');
const helmet = require('helmet');
const cors = require('cors');
const commonPath = require('../config/common-paths');

require('dotenv').config();

const app = express();

const POLICY_NONE = ["'none'"];
const POLICY_SELF = ["'self'"];

app.use(helmet());
app.use(helmet.referrerPolicy({ policy: 'same-origin' }));
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: POLICY_SELF,
      connectSrc: POLICY_SELF,
      fontSrc: POLICY_SELF,
      imgSrc: POLICY_SELF.concat(['blob:', 'data:']),
      manifestSrc: POLICY_SELF,
      mediaSrc: POLICY_SELF.concat(['*.nodediggity.com']),
      objectSrc: POLICY_NONE,
      scriptSrc: POLICY_SELF,
      styleSrc: POLICY_SELF,
      workerSrc: POLICY_SELF,
      formAction: POLICY_SELF,
      frameAncestors: POLICY_NONE,
      blockAllMixedContent: true,
      upgradeInsecureRequests: false,
    },
  })
);

app.options('*', cors({ optionsSuccessStatus: 200 })); // some legacy browsers (IE11, various SmartTVs) choke on 204

app.use(
  '/',
  expressStaticGzip(commonPath.outputPath, { indexFromEmptyFile: false })
);


app.get('/healthz', (_, res) => res.send('OK'));
app.get('*', (_, res) => res.sendFile(commonPath.outputPath + '/index.html'));

const PORT = process.env.SERVER_PORT || 3000;
const HOST = process.env.SERVER_HOST || 'localhost';

app.listen(PORT);
console.log(`API started on ${HOST}:${PORT}`);

Webpack构建配置

const commonPaths = require('../common-paths');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = {
  context: commonPaths.srcPath,
  entry: {
    signal: ['babel-polyfill', './signal/app'],
  },
  output: {
    filename: '[name].js',
    path: __dirname + '/dist',
    chunkFilename: '[id].[chunkhash].js',
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      { test: /\.(jsx?)$/, exclude: /node_modules/, use: ['babel-loader'] },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'postcss-loader'],
        }),
      },
      {
        test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
        },
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Web App',
      template: commonPaths.projectRoot + '/public/index.html',
      inject: 'body',
      minify: {
        collapseWhitespace: true,
        removeComments: true,
        removeRedundantAttributes: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true,
      },
    }),
    new ExtractTextPlugin({
      filename: 'static/[name].[hash].min.css',
    }),
    new CompressionPlugin({
      algorithm: 'gzip',
      test: /\.(j|cs)s$/,
      threshold: 10240,
      minRatio: 0.8,
      deleteOriginalAssets: process.env.NODE_ENV === 'prod',
    }),
  ],
};

我的index.html已加载,但是未应用任何样式或js,并且控制台出现以下错误

Refused to apply style from 'http://localhost:3000/static/signal.ab8a8afea9d967e4bd23.min.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

与捆绑的JS文件相同。如果我关闭gzip,那么它可以正常工作。

文件夹结构

Folder Layout

奇怪的是,如果我在浏览器中请求css文件,并附加.gz扩展名,则文件将下载。因此,我相信文件夹结构是可以的,因为如果我只是删除gzip压缩,这也可以使用。

公用路径

const path = require('path');
const PROJECT_ROOT = path.resolve(__dirname, '../');

module.exports = {
  projectRoot: PROJECT_ROOT,
  serverPath: path.join(PROJECT_ROOT, 'server'),
  srcPath: path.join(PROJECT_ROOT, 'src'),
  appPath: path.join(PROJECT_ROOT, 'src/app'),
  signalPath: path.join(PROJECT_ROOT, 'src/signal'),
  outputPath: path.join(PROJECT_ROOT, 'dist'),
};

Common-paths.js位于配置文件夹中。

0 个答案:

没有答案