无法使用node.js和express来提供图像(png)

del*_*247 5 node.js

我已经在SO上研究了类似的问题,但是没有找到解决我问题的方法......我已经建立了一条快速路线来提供图像,但是我不能让它从存储的位置返回图像.注意我已经包含了一个声明,允许来自任何来源的请求.会发生的是,当我向http://localhost:8080/images/x10.png响应发出请求时,我得到的是一个空的图像元素src="http://localhost:8080/images/x10.png而不是from http://ubuntubox.dev/images/x10.png,这是图像实际所在的位置,并且是我最终传递给请求方法的路径.我错过了什么?谢谢.

app.get('/images/*', function(req, res, path){
  var imagePath = req.url,
      url = 'http://ubuntubox.dev' + imagePath;

  request(url, function(error, response, img) {
    if(!error && response.statusCode === 200) {
      res.header('Access-Control-Allow-Origin', '*');
      res.writeHead(200, {'Content-Type': 'image/png' });
      res.end(img, 'binary');
    } else if(response.statusCode === 404) {
      res.status(404);
      res.type('txt').send('oops');
    }
  });
}).listen(8080, '127.0.0.1');
Run Code Online (Sandbox Code Playgroud)

Ser*_*ino 6

我不知道你是否还有这个问题,但..

您的问题的解决方案只是放一个.pipe(res),它会将文件发送到响应

app.get('/images/*', function(req, res, path){
  var imagePath = req.url,
      url = 'http://ubuntubox.dev' + imagePath;

  request(url).pipe(res);
}).listen(8080, '127.0.0.1');
Run Code Online (Sandbox Code Playgroud)


use*_*041 0

刚刚在 Express 4 中为自己解决了这个问题

app.get('/images/img1.png', function(req, res){
  res.sendFile('/Absolute/path/to/the/file/images/img1.png');
});
Run Code Online (Sandbox Code Playgroud)

  • 我猜这没有用..你不能为每个图像编写一条路线..比如img1..img2..等等并发送该文件作为响应 (4认同)