SyntaxError:在使用gzip提供文件时,仅在firefox中抛出非法字符

时间:2018-02-07 11:56:53

标签: javascript firefox gzip

我使用webpack使用compress插件将我的应用程序捆绑到bundle.gzip。

new CompressionPlugin({
  asset: '[path].gz[query]',
  algorithm: 'gzip',
  test: /\.js$|\.css$|\.html$/,
  threshold: 10240,
  minRatio: 0.8,
}),

然后我有一个快速服务器,提供Web包捆绑的所有内容,并为响应添加内容编码。

const path = require('path')
const express = require('express')

const app = express()
const server = require('http').createServer(app)

app.get('*.js', (req, res, next) => {
    req.url = `${req.url}.gz`
    res.set('Content-Encoding', 'gzip')
    next()
})

app.use(express.static(path.resolve(__dirname, 'dist')))
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/index.html'))
})
// eslint-disable-next-line
console.log("Server listening on port 8500")
server.listen(8500)

除了firefox之外,每个浏览器都能很好地工作,当我打开控制台时会看到这个。

enter image description here

问题是什么我觉得这个问题与内容编码

有关

1 个答案:

答案 0 :(得分:3)

您需要为回复设置Content-Type

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

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