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.
JavaScript
x
11
11
1
fetchImages = () => {
2
const imageName = 'garande.png'
3
const url = `http://localhost:5000/fetchImage/${imageName}`
4
axios.get(url, {responseType: 'blob'})
5
.then(res => {
6
return(
7
<img src={res.data} alt="trial" />
8
)
9
}
10
}
11
And this what I have in the server.js file in the backend
JavaScript
1
7
1
app.get('/fetchImage/:file(*)', (req, res) => {
2
let file = req.params.file;
3
let fileLocation = path.join('../Backup/images/', file);
4
//res.send({image: fileLocation});
5
res.sendFile(`${fileLocation}`)
6
})
7
I expect the Image to show up in the users page. Thanks.
Advertisement
Answer
This worked for me:
JavaScript
1
41
41
1
export async function get(url: string) {
2
try {
3
const response = await fetch(url, {
4
method: 'GET', // *GET, POST, PUT, DELETE, etc.
5
mode: 'cors', // no-cors, *cors, same-origin
6
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
7
headers: {
8
'Content-Type': 'image/jpeg'
9
}
10
})
11
const blob = await response.blob()
12
return [URL.createObjectURL(blob), null];
13
}
14
catch (error) {
15
console.error(`get: error occurred ${error}`);
16
return [null, error]
17
}
18
}
19
20
function foo(props: any) {
21
const [screenShot, setScreenshot] = useState(undefined)
22
const url = props.url
23
useEffect(() => {
24
async function fetchData() {
25
// You can await here
26
const [response, error] = await get(url)
27
if (error)
28
log(error)
29
else {
30
log(`got response ${response}`)
31
setScreenshot(response)
32
}
33
}
34
fetchData();
35
}, [url])
36
37
return <div>
38
<img src={screenShot} className="Screenshot" alt="showing screen capture" />
39
</div>
40
}
41