Send image path from node.js express server to react client

10,439

You've not really supplied much code here but from what I gather you've got the images in a public/images directory and then you're sending the image path back to the client and you want the client to be able to pull the image.

From that I'm going to assume what you want is the Express server static functionality. This will allow you to serve up the static content from the public/images directory.

The documentation will show you how to setup serving static files and then your frontend should have no problems displaying the images.

Share:
10,439
Edi Afremov
Author by

Edi Afremov

Updated on June 05, 2022

Comments

  • Edi Afremov
    Edi Afremov almost 2 years

    I want to build api that store images and send them to react client app.

    The images are located in the express app in the public/images folder.

    I want to send the data obj to the client with the image path inside.

    Express.js:

    var express = require('express');
    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var cors = require('cors');
    
    var index = require('./routes/index');
    var users = require('./routes/users');
    var login = require('./routes/login');
    var signup = require('./routes/signup');
    var clothing = require('./routes/clothing');
    
    var app = express();
    app.use(cors());
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'pug');
    
    // uncomment after placing your favicon in /public
    //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.use('/', index);
    app.use('/users', users);
    app.use('/login', login);
    app.use('/signup', signup);
    app.use('/clothing', clothing);
    
    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
    });
    
    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};
    
      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });
    
    module.exports = app;
    

    Server:

    const data = {
      products: [
        {
          id: 1,
          type: 'jeans',
          price: 100,
          brand: 'Levis',
          size: ['s', 'm', 'l'],
          color: 'Black',
          image: '/images/levis.png'
        },
        {
          id: 2,
          type: 'shirt',
          price: 150,
          brand: 'Tommy Hilfiger',
          size: ['s', 'm', 'l', 'xl'],
          color: 'White',
          image: '/images/tommy.png'
        },
        {
          id: 3,
          type: 'T-shirt',
          price: 30,
          brand: 'Levis',
          size: ['s', 'm', 'l'],
          color: 'Black',
          image: '/images/polo.png'
        }
      ]
    };
    
    router.get('/', function(req, res, next) {
      res.send(data);
    });
    

    Client:

    Here in the react app i want to fetch the image path and render it.

    import React, { Component } from 'react';
    import { withRouter, Link, Route } from 'react-router-dom';
    import Shoes from './../Shoes/Shoes';
    import axios from 'axios';
    class clothing extends Component {
      state = {
        products: []
      };
      componentDidMount() {
        axios({
          method: 'get',
          url: 'http://localhost:3001/clothing'
        }).then(response => {
          this.setState({
            products: response.data.products
          });
        });
      }
      render() {
        let productsList = this.state.products;
        const products = Object.keys(productsList).map((product, id) => {
          return (
            <div key={id} className="product">
              <img src={productsList[product].image} />
              <h3>{productsList[product].brand}</h3>
              <h3>{productsList[product].price}</h3>
            </div>
          );
        });
        return <div className="clothing-container">{products}</div>;
      }
    }
    
    export default withRouter(clothing);
    

    Thanks!

    • Aaqib
      Aaqib about 6 years
      Is there any error you are getting in console?
    • Edi Afremov
      Edi Afremov about 6 years
      No, The image isn't found
    • Edi Afremov
      Edi Afremov about 6 years
      The http request is work, i can't get the image but the rest i get.
    • Aaqib
      Aaqib about 6 years
      So you can't get the link of the image i.e : /images/polo.png or the image on the screen ?
    • Edi Afremov
      Edi Afremov about 6 years
      Yes, i'm getting the alt property..
    • Aaqib
      Aaqib about 6 years
      I can’t see any alt property in the above code
  • Elliot Blackburn
    Elliot Blackburn about 6 years
    You have clashing routes, make the serve static go from a /blob or /static endpoint and update your data. Or remove your controller code for the / endpoint as this will be clashing.
  • Darshn
    Darshn over 5 years
    The documentation link which you provided was really helpful. It solved the my issue. Thanks alot :)