i'm trying to load a list of wallpapers from local storage that i already post them and saved their paths in mongoDB.
So i'm trying to loop through the array of paths and use each path as src in each img tag
the main.js ponent :
import React, { Component } from 'react'
export default class Main extends Component {
state = {
data : []
}
ponentDidMount(){
fetch('http://localhost:5000/').then(res => res.json())
.then(data=> this.setState({data}))
}
render() {
console.log(this.state.data)
return (
<div>
<h1>Main</h1>
{this.state.data ? this.state.data.map(img =>
(<div key={img._id}>{img ? <img src={require(`${img.img.path}`)}
alt={img.img.name}/>:<span>deleted</span>}</div>)):
<h3>loading</h3>}
</div>
)
}
}
the server code :
server.get('/', (req, res)=>{
Wallpaper.find({}, (err, result)=>{
if(err) {
res.json({msg: err})
}else{
res.json(result)
}
})
})
it should return the images in the uploads folder in the react app but it returns this error:
Error: Cannot find module '/home/ahdy/Workspace/Wally/wallcraft/public/uploads/ak47456193147469824_n.jpg'
i'm trying to load a list of wallpapers from local storage that i already post them and saved their paths in mongoDB.
So i'm trying to loop through the array of paths and use each path as src in each img tag
the main.js ponent :
import React, { Component } from 'react'
export default class Main extends Component {
state = {
data : []
}
ponentDidMount(){
fetch('http://localhost:5000/').then(res => res.json())
.then(data=> this.setState({data}))
}
render() {
console.log(this.state.data)
return (
<div>
<h1>Main</h1>
{this.state.data ? this.state.data.map(img =>
(<div key={img._id}>{img ? <img src={require(`${img.img.path}`)}
alt={img.img.name}/>:<span>deleted</span>}</div>)):
<h3>loading</h3>}
</div>
)
}
}
the server code :
server.get('/', (req, res)=>{
Wallpaper.find({}, (err, result)=>{
if(err) {
res.json({msg: err})
}else{
res.json(result)
}
})
})
it should return the images in the uploads folder in the react app but it returns this error:
Error: Cannot find module '/home/ahdy/Workspace/Wally/wallcraft/public/uploads/ak47456193147469824_n.jpg'
Share
Improve this question
asked Jul 18, 2019 at 13:36
ahdy kefiahdy kefi
451 gold badge1 silver badge7 bronze badges
2
-
Why the
require()
call? If those images are in some folder on the server, just thesrc
directly to their URL. – user5734311 Commented Jul 18, 2019 at 13:43 -
this.state.data ?
will be true anyways, usethis.state.data.length ?
– julian libor Commented Jul 18, 2019 at 13:59
1 Answer
Reset to default 1This
<img src={require(`${img.img.path}`)}
should be
<img src={`/uploads/${img.img.path}`}
no need of require
here
NB: put correct path there