简体   繁体   English

调整大小的图像,以将响应设置响应标头表达为“ Content-Length:0”,并且没有响应数据

[英]Piping resized image to express response setting response header to 'Content-Length:0' and no data in response

I am building a dummy image generator to improve my understanding of Node and Express. 我正在构建一个虚拟图像生成器,以提高对Node和Express的理解。 I get the dimensions from the URL and use GM package to resize it. 我从URL获取尺寸,并使用GM包调整尺寸。 The resulting stream is piped into the response. 生成的流通过管道传递到响应中。 But I don't get the data on the front end and when I check the response tab in the Network panel of the dev tools in Chrome I see 'this response has no data available'. 但是我没有在前端获得数据,当我在Chrome开发工具的“网络”面板中检查“响应”选项卡时,看到“此响应没有可用数据”。 Can someone please give me some pointers as I am not sure where I can begin debugging this. 有人可以给我一些指示,因为我不确定从哪里可以开始调试它。

const IMAGE_DIR_PATH = path.join(__dirname, './../../data/images');

const getRandomImageName = () => {
  return new Promise((resolve, reject) => {
    fs.readdir(IMAGE_DIR_PATH, (err, images) => {
      err ? reject(err) : resolve(
        images[Math.floor(Math.random() * images.length)]
      );
    });
  });
};

const pickDimensions = (dimensionsStr) => {
  const dimensions = dimensionsStr.toLowerCase().split('x');
  return {
    width: dimensions[0],
    height: dimensions[1] ? dimensions[1] : dimensions[0]
  };
};

exports.getRandomImageByDimension = (req, res, next) => {
  const dimensions = pickDimensions(req.params.dimensions);

  //getRandomImageName returns a Promise
  //resolves with the name of the file example: abc.jpg
  getRandomImageName()
  .then((img) => {
    res.set('Content-Type', 'image/jpeg');

    //I am getting the right image and the path below is valid
    gm(path.resolve(`${IMAGE_DIR_PATH}/${img}`))
    .resize(dimensions.width, dimensions.height)
    .stream(function (err, stdout, stderr) {
      if (err) { throw new Error(err); }
      stdout.pipe(res);
    });
  })
  .catch(e => {
    res.status(500);
    res.send(e);
  });
};

The response headers I receive is shown below: 我收到的响应头如下所示: 在此处输入图片说明

Turns out that I had forgotten to add ImageMagick as a dependency for gm and this was causing an error. 原来我忘了添加ImageMagick作为gm的依赖项,这导致了错误。 Strangely the error was not shown in the console and I found it only after breaking down the app into simpler pieces and debugging as skirtle mentioned in a comment above. 奇怪的是,该错误未在控制台中显示,只有在将应用程序分解为更简单的部分并按照上面的注释中提到的方式调试后,我才发现它。

To fix I did the following: 为了解决这个问题,我做了以下工作:

npm install --save imagemagick

Then in the file where I was using the gm package, I set the imageMagick property: 然后在我使用gm包的文件中,设置imageMagick属性:

const gm = require('gm').subClass({imageMagick: true});

Note: I was running this on a Windows 7. 注意:我是在Windows 7上运行的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM