在 express 中管道(代理)图像流会产生一个空框

Piping (proxying) an image stream in express produces an empty box

我正在尝试使用 NodeJS Express 将图像响应从内部 API 传输到外部端点。 IE。代理图像。

这是我尝试过的方法,但我总是得到一个空框而不是图像:

app.get('/image', (req, res) => {
    res.setHeader('Content-Type', 'image/png');
    request.get(`http://localhost:8080/image`).pipe(res);
    
    // Also tried reading from a file and not the endpoint 
    //to make sure it's not a problem  with "request" library with same results
    //fs.createReadStream('./image.png').pipe(res);
});

使用浏览器开发工具,我还可以看到我在外部端点上获得的空图像的大小大于从内部端点获得的工作图像的大小。

从“Postman”访问端点似乎没有问题,但从 Firefox 访问却说图像有错误。

所以这似乎是某种编码问题,我似乎无法弄清楚如何解决。请帮忙。

无法重现您的问题。下面的例子工作正常。测试环境:

  • 微软边缘 86.0.622.38

例如

server-internal.ts:

import express from 'express';
import fs from 'fs';
import path from 'path';

const app = express();
const port = 8080;

app.get('/image', (req, res) => {
  console.log('internal server /image');
  res.setHeader('Content-Type', 'image/png');
  fs.createReadStream(path.resolve(__dirname, './image.png')).pipe(res);
});

app.listen(port, () => console.log('HTTP server is listening on port:', port));

server-external.ts:

import express from 'express';
import request from 'request';

const app = express();
const port = 3000;

app.get('/image', (req, res) => {
  console.log('external server /image');
  res.setHeader('Content-Type', 'image/png');
  request.get(`http://localhost:8080/image`).pipe(res);
});

app.listen(port, () => console.log('HTTP server is listening on port:', port));

访问http://localhost:3000/image,正确获取图像。

内部服务器的日志:

HTTP server is listening on port: 8080
internal server /image

外部服务器的日志:

HTTP server is listening on port: 3000
external server /image

源代码:https://github.com/mrdulin/expressjs-research/tree/master/src/Whosebug/64302729

感谢 slideshowp2 花时间指出,我提供的代码应该确实有效。

我提供的信息不可能找出问题所在。

我在我的项目中使用了“livereload”中间件。

此中间件与来自我的服务器的所有响应相交,并尝试将 liverelad 脚本注入其中。

默认情况下,它配置为忽略以“.png”和其他图像和二进制格式结尾的端点的响应。

将“.png”添加到端点路径,解决了问题。

app.get('/image.png', (req, res) => {
    request.get(`http://localhost:8080/image`).pipe(res);
});