Q1) In my reactjs application, I am trying to fetch an API from my backend Nodejs server. The API responds with an image file on request.
I can access and see image file on http://192.168.22.124:3000/source/592018124023PM-pexels-photo.jpg
But in my reactjs client side I get this error on console log.
Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0
Reactjs:
let fetchURL = 'http://192.168.22.124:3000/source/'; let image = name.map((picName) => { return picName }) fetch(fetchURL + image) .then(response => response.json()) .then(images => console.log(fetchURL + images));
Nodejs:
app.get('/source/:fileid', (req, res) => { const { fileid } = req.params; res.sendFile(__dirname + /data/ + fileid); });
Is there any better way to do than what I am doing above?
Q2) Also, how can I assign a value to an empty variable (which lives outside the fetch function)
jpg = fetchURL + images; So I can access it somewhere.
To get an image from API with JavaScript Fetch API, we can call the response's blob method and use the FileReader to read the file into a base64 string. We create the FileReader instance and set the onloadend property to a function that gets the base64 string from reader. result .
To use fetch API to Get an image from a URL, we can call the blob method on the response object. Then we can use FileReader to read the blob into a base64 string. We call fetch with imageUrl to make a GET request to the imageUrl and return a promise with the response object.
Summary. The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() .
The response from the server is a binary file, not JSON formatted text. You need to read the response stream as a Blob.
const imageUrl = "https://.../image.jpg"; fetch(imageUrl) // vvvv .then(response => response.blob()) .then(imageBlob => { // Then create a local URL for that image and print it const imageObjectURL = URL.createObjectURL(imageBlob); console.log(imageObjectURL); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With