Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
60
rated 0 times [  63] [ 3]  / answers: 1 / hits: 157177  / 6 Years ago, wed, may 9, 2018, 12:00:00

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.


More From » node.js

 Answers
7

The response from the server is an image file, not JSON formatted text.
You'll want to read the response content with Response.blob(), blob meaning "binary large object".


In this function we fetch a blob:


async function fetchBlob(url) {
const response = await fetch(url);

// Here is the significant part
// returning a blob instead of json
return response.blob();
}

Then, you can create an object URL and assign the source of an image to this generated URL in your React application:


const [imageSourceUrl, setImageSourceUrl] = useState("");

const downloadImageAndSetSource = async (imageUrl) => {
const image = await fetchBlob(imageUrl);
setImageSourceUrl(URL.createObjectURL(image));
}

[#54480] Friday, May 4, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
masonm

Total Points: 167
Total Questions: 87
Total Answers: 103

Location: Rwanda
Member since Wed, Jun 8, 2022
2 Years ago
;