首页 > 解决方案 > 如何使用 Fetch 在前端显示通过 HTTP (Node.js) 发送的图像?

问题描述

我正在尝试使用 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

标签: javascripthtmlnode.jshttp

解决方案


直接在 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


推荐阅读