PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 12, 2022

[FIXED] How to Fetch and Display an Image from an express backend server to a React js frontend?

 October 12, 2022     axios, express, javascript, node.js, reactjs     No comments   

Issue

I'm trying to fetch images from an express backend and display them in the react js frontend. How can I achieve this perfectly?

I have tried to fetch the images saved in my backend folder named "Backup" and display them back to the user in the react js frontend. I have tried this using axios but still am getting an invalid image instead of the correct image.

Below is my fetch request in the frontend.

fetchImages = () => {
    const imageName = 'garande.png'
    const url = `http://localhost:5000/fetchImage/${imageName}`
    axios.get(url, {responseType: 'blob'})
    .then(res => {
        return(
            <img src={res.data} alt="trial" />
        )
    }
}

And this what I have in the server.js file in the backend

app.get('/fetchImage/:file(*)', (req, res) => {
    let file = req.params.file;
    let fileLocation = path.join('../Backup/images/', file);
    //res.send({image: fileLocation});
    res.sendFile(`${fileLocation}`)
})

I expect the Image to show up in the users page. Thanks.


Solution

This worked for me:

export async function get(url: string) {
    try {
        const response = await fetch(url, {
            method: 'GET', // *GET, POST, PUT, DELETE, etc.
            mode: 'cors', // no-cors, *cors, same-origin
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            headers: {
                'Content-Type': 'image/jpeg'
            }
        })
        const blob = await response.blob()
        return [URL.createObjectURL(blob), null];
    }
    catch (error) {
        console.error(`get: error occurred ${error}`);
        return [null, error]
    }
}   

function foo(props: any) {
const [screenShot, setScreenshot] = useState(undefined)
const url = props.url
useEffect(() => {
    async function fetchData() {
        // You can await here
        const [response, error] = await get(url)
        if (error)
            log(error)
        else {
            log(`got response ${response}`)
        setScreenshot(response)
        }
    }
    fetchData();
}, [url])

return <div>
    <img src={screenShot} className="Screenshot" alt="showing screen capture" />
</div>
}


Answered By - Steve
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing