繁体   English   中英

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

[英]How to display an Image sent through HTTP (Node.js) in the Front End using Fetch?

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

前端

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM