如何在express/nodejs中的静态gzip文件中添加标头? [英] How to add headers to static gzip file in express/nodejs?

查看:459
本文介绍了如何在express/nodejs中的静态gzip文件中添加标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些无法从Unity构建中添加标头的文件.它们具有jsgz,memgz和datagz扩展名.它们位于NodeJs项目中的公用文件夹中. 我正在使用Express 4并设置了Compression,但是我相信这只会压缩现有文件以进行传输,而不处理已经压缩的文件. 我尝试使用app.get添加标题,但似乎不起作用:

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'
          }
  }
...

我尝试通过使用res.set并首先设置它们来设置标头,然后让next()调用来处理响应,但是每当我取回文件时,它就是gzip文件而没有多余的标头,浏览器无法理解. 我尝试过的方法确实添加了其他标头(摆动","x时间戳"等),因此我认为其他方法正在拦截这些特定标头. 如何才能返回这些压缩文件,以便浏览器理解它们?

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?

推荐答案

您可以使用 express- static-gzip 作为Express中间件,如下所示:

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'));

这篇关于如何在express/nodejs中的静态gzip文件中添加标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆