如何使用Fetch在前端显示通过HTTP(Node.js)发送的图像



我正在尝试获取URL(http://localhost)它将使用Node.js.通过HTTP返回一张图片(此时,扩展无关紧要(

前端

let image = await fetch('http://localhost:3031', {
mode: 'cors',
method: 'GET'
})

后端

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
res.setHeader('Content-Type', 'image/png');
fs.readFile('image.png', (err, data) => {
res.write(data, "binary");
res.end();
});
}).listen(3031)

我想拍下那张照片,然后把它显示在网站上。

我正在获取文件,而不是SRC

直接在HTML中显示为:

<img id="loadedimage" src="http://localhost:3031/"/>

或者使用fetch,使用createObjectURL:

var element = document.getElementById('loadedimage');
var response = await fetch('http://localhost:3031');
var image = await response.blob();
element.src = URL.createObjectURL(image);

工作演示:https://codepen.io/bortao/pen/oNXpvYR

最新更新