Home > Software engineering >  How to get the image from backend using react and nodejs
How to get the image from backend using react and nodejs

Time:09-03

Good morning. I'm using ReactJS and NodeJS to create a Housing blog. I created the login controller in NodeJS and send the user details to frontend including the image path from the database.

The image path is created and stored in the DB like: http://localhost:3000/images/image-name.jpg or png, jpeg...

This is the folder where I stored the images:

enter image description here

The backend middleware doesn't throw any errors, but for reference I will paste it here:

app.post('/api/login', async (req, res, next) => {
    // Move this on top of page
    const bcrypt = require('bcrypt');
    const User = require('./models/User');

    const {email, password} = req.body;

    try {
        const userRequired = await User.find({email});
        if (userRequired.length > 0) {
            const match = await bcrypt.compare(password, userRequired[0].password);
            if (match) return res.status(200).send({
                _id:        userRequired[0]._id,
                fName:      userRequired[0].fName,
                lName:      userRequired[0].lName,
                avatar:     userRequired[0].avatar.length > 0 ? userRequired[0].avatar : null,
                email:      userRequired[0].email,
                joined:     userRequired[0].created
            });
            else return res.status(404).send('Wrong credentials.');
        }
        else {
            return res.status(404).send('Wrong credentials.');
        } 
    } 
    catch (error) {
        return res.status(500).send(error);
    }
});

On the front end side, the login function store the user object that is containing the avatar link (http://localhost:3000/images/image-name.jpg);

onst Profile = () => {

  const userDetails = JSON.parse(sessionStorage.getItem('user'));

  return (
    // Main wrapper
    <ProfileWrapper>
      
      {/* Profile holder with avatar */}
      <ProfileInfo>

        <img src={userDetails.avatar} />

        {/* <ProfileAvatar alt='Profile avatar' src={userDetails.avatar}/> Image tag with react-style-component */}
      </ProfileInfo>


    </ProfileWrapper>
  )
}

If I log in the console the userDetails.avatar there is no error. I tried also to stringfy it and set the SRC with the string but there is 404 error in the console all the time... enter image description here

I also tried to split the link and set the SRC by the server path like

<img src='./image/imagenumber.jpg'/>

But again, there is no effect.

What I am doing wrong? Thanks.

CodePudding user response:

You can provide static content via your express app using the static middleware:

const app = express();
app.use('/images', express.static(path.join(__dirname, 'images')));

Check this answer for more information.

  • Related