2

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

5
  • you mean setting the src of an image-tag? Can you post your html codes? Commented Mar 9, 2020 at 1:30
  • Is not the src I need, because I'm passing the complete file through HTTP Commented Mar 9, 2020 at 1:33
  • There is probably no point in fetching an image at all on the Client. Just use <img src='yourSource.png' /> in HTML or imgElement.src = 'yourSource.png'; in Front End JavaScript. Commented Mar 9, 2020 at 1:46
  • The thing is im using TWAIN and WAI in the command line to get the picture from an Scanner. So you mean i have to upload that picture to another server soIi can get a src Commented Mar 9, 2020 at 2:00
  • If you're serving the image at http://localhost:3031, that's what you set its src to, i.e. <img src="http://localhost:3031" />. Usually, you only need to fetch the image in your script if you want to somehow process its binary data. Commented Mar 9, 2020 at 2:43

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what i was looking for. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.