无法提供带有节点的图像 (png.js 和表达

  • 本文关键字:png js 图像 节点 node.js
  • 更新时间 :
  • 英文 :


我已经研究了关于SO的类似问题,但没有找到解决问题的方法......我已经设置了一条快速路由来提供图像,但我无法让它从存储位置返回图像。 请注意,我包含一个语句来允许来自任何源的请求。发生的情况是,当我发出请求http://localhost:8080/images/x10.png时,我得到的响应是一个空的图像元素,带有src="http://localhost:8080/images/x10.png而不是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');

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

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

如果您想以有意义的方式提供图像和其他资产,并且不需要您编写一百万条路由,请尝试以下操作:

  1. 创建一个"公共"新文件夹,并将所有资产移入其中。
  2. 打开服务器.js并添加以下行:

app.use(express.static('public'))

您的资产现在应该可用,如下所示:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

苏尔: https://expressjs.com/en/starter/static-files.html

刚刚在快递 4 中为自己弄清楚了这一点

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

user2879041 已经回答了他认为有用的问题,但我仍然会想到另一种提供图像的方法,(我不会手动为每个文件编写路由并将文件发送到浏览器)。

由于您已经在使用 express,只需直接服务器静态图像,您已经在express.static

app.use(express.static('/Absolute/path/to/the/file/images/img1.png'));

使用express.static的好处是,您只需在要静态的文件夹中不断添加图像,Express将为您提供图像(无需添加任何代码)。

我不确定是否是相同的情况。

但这是我的答案:

var path = require('path');
var express = require('express');
var app = express();
var dir = path.join(__dirname, 'public');
app.use('/public', express.static(dir));
app.listen(3000, function () {
console.log('Listening on http://localhost:3000/');
});

请注意此行:

app.use('/public', express.static(dir));

您需要使用app.use方法再次添加路径 我不明白添加这部分的想法,但这是使其工作的唯一方法。 没有它,它一直响应"错误",我无法访问此文件。

希望我能帮到你。

最新更新