[英]How to display an Image sent through HTTP (Node.js) in the Front End using Fetch?
I'm trying to Fetch a URL ( http://localhost ) that will return a picture (At this moment, the extension doesn't matter) through HTTP using Node.js.我正在尝试使用 Node.js 通过 HTTP 获取将返回图片的 URL ( http://localhost )(此时,扩展名无关紧要)。
Front End前端
let image = await fetch('http://localhost:3031', {
mode: 'cors',
method: 'GET'
})
Back End后端
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)
I want to take that picture and then display it into the Website.我想拍下那张照片,然后将其显示在网站上。
Im getting the file, NOT THE SRC我正在获取文件,而不是 SRC
Directly in the HTML as:直接在 HTML 中作为:
<img id="loadedimage" src="http://localhost:3031/"/>
Or with fetch
, using createObjectURL
:或者使用
fetch
,使用createObjectURL
:
var element = document.getElementById('loadedimage');
var response = await fetch('http://localhost:3031');
var image = await response.blob();
element.src = URL.createObjectURL(image);
Working demo: https://codepen.io/bortao/pen/oNXpvYR工作演示: https : //codepen.io/bortao/pen/oNXpvYR
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.