简体   繁体   中英

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.

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

Directly in the HTML as:

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

Or with fetch , using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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