简体   繁体   English

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

[英]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.

相关问题 如何使用Node JS在前端显示存储在modgodb中的图像URL路径 - How to display image URL path stored in modgodb in the front end using node js 如何使用 Node.js 服务器将我的图像数据从前端保存到 Mongoose 数据库 - How can I save my image data from front end to Mongoose database using Node.js server 如何使用 node.js 向前端发送成功状态码? - How do i send a success status code to the front end using node.js? 前端 JS 获取(POST)请求作为 GET 发送? - Front end JS fetch(POST) request being sent as a GET? Node.js-jQuery。 从服务器获取PDF并显示在前端 - Node.js - jQuery. Get PDF from server and display on front-end 如何提前结束node.js http请求 - How to end a node.js http request early 如何在node.js ejs模板中将变量从后端传递到前端 - How to pass variable from back-end to front-end in node.js ejs template 如何使用 Node.js 显示从 http 请求到外部 API 的图像 - How to display image from http request to external API with Node.js 如何使用node.js后端服务器与前端和mongolab数据库进行交互? - How to use a node.js back-end server to interact with the front-end and a mongolab database? 如何使用后端 Node.js Express-Sessions 对 React 前端进行身份验证? - How to authentication React Front End with back-end Node.js Express-Sessions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM