Search code examples
reactjsnode.jsaxiosmulter

Image shows correctly in network "Preview" but on its response.data it's all broken gibberish


My issue is the following

Inside /uploads/{userid}/ there is a single image I named user-pf.png, I can access that folder just right and retrieve the image from it, but my frontend doesn't display it properly, even though it can "see" the image just right, as images below will show.

This is the code I have on my frontend (REACT) and my backend (NodeJS)

import api from '../../service';
  const myProfile = () => {
  const { user, updateUser } = useUser();
  const [foto, setFoto] = useState(PlaceholderPicture);

useEffect(() => {
   if (user) {
     api
      .get(`/uploads/${user.id}/user-pf.png`)
      .then((response) => {
         console.log('response', response);
         setFoto(response.data);
   })
       .catch((error) => {
             console.error('Error fetching image:', error);
    );
    }
[user]);

...
<img
       className="my-picture"
       src={foto ? foto : PlaceholderPicture}
       alt="Profile"
/>

//nodejs

app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

I tried converting response.data to binary and use it but it also didn`t work because it doesn't look like it is binary.

I tried also saving the image in the db but it didn't work properly, it was giving me a headache so i did that easier approach but the image is now not displaying correctly.

I don't know what else to do , I tried youtube videos and theyre all similar to my implementation but just here it doesn't work

GET 200

Image on Preview

Response.data is broken


Solution

  • You seem to use axios, so you could just tell axios to fetch image as a blob, and then convert it to URL with URL.createObjectURL and assign it to img tag:

    // change your `api` service to recieve config parameter
        axios
          .get(`/uploads/${user.id}/user-pf.png`, {
                responseType:'blob'
              })
          .then((response) => {
            console.log('response', response);
            setFoto(URL.createObjectURL(response.data));
          })
          .catch((error) => {
              console.error('Error fetching image:', error);
            );
          }
    

    or you could simply assign /uploads/${user.id}/user-pf.png to img tag, as the image is served from public folder