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

无人久伴 提交于 2020-01-24 17:42:33

问题


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.

来源:https://stackoverflow.com/questions/57829529/how-to-fetch-and-display-an-image-from-an-express-backend-server-to-a-react-js-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!