最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

运维笔记admin14浏览0评论

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

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

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

app.get('/images/*', function(req, res, path){
  var imagePath = req.url,
      url = '' + 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');
回答如下:

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

您的问题的解决方案只是放一个.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');
发布评论

评论列表(0)

  1. 暂无评论