How to add headers to static gzip file in express/nodejs?

别说谁变了你拦得住时间么 提交于 2019-12-22 18:00:37

问题


I have some files, from a Unity build, that I am unable to add headers to. They have extensions jsgz, memgz and datagz. They are located in my public folder within my NodeJs project. I am using Express 4 and have set up Compression but I believe that this only compresses existing files for transmission, and does not handle files that are already compressed. I have tried using app.get to add headers but it doesn't seem to work:

app.get('/blah/unitymodels/Release/widget.js', function(req, res, next) {
  ... Check ['accept-encoding'] ...
  if (acceptsGzip) {
      var gzippedPath = req.url + 'gz';
      res.sendFile(gzippedPath, {
          root: './public',
          headers: {
              'Content-Encoding': 'gzip',
              'Content-Type': 'application/javascript'
          }
  }
...

I have tried setting the headers like this, by using res.set and by setting them first then letting the next() call handle the response but whenever I get the file back it is just the gzip file without the extra headers and the browser does not understand it. The approaches I have tried do add other headers ('wibble', 'x-timestamp', etc) so I assume that something else is intercepting these specific ones. How am I able to return these gzipped files so that the browser understands them?


回答1:


You can use express-static-gzip as Express middleware as shown below:

/* here serves gzipped static files */
app.use('/my_static/zipped/', expressStaticGzip('my_static/zipped/', {
    customCompressions: [{
        encodingName: "gzip",
        fileExtension: "gz"
    }]
}));

/* here serves other static files */
app.use('/my_static', express.static('my_static'));


来源:https://stackoverflow.com/questions/35774707/how-to-add-headers-to-static-gzip-file-in-express-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!