2

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!

6
  • Is there any error you are getting in console? Commented Feb 21, 2018 at 20:51
  • No, The image isn't found Commented Feb 21, 2018 at 20:57
  • The http request is work, i can't get the image but the rest i get. Commented Feb 21, 2018 at 21:06
  • 1
    So you can't get the link of the image i.e : /images/polo.png or the image on the screen ? Commented Feb 21, 2018 at 21:33
  • Yes, i'm getting the alt property.. Commented Feb 22, 2018 at 7:55

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
The documentation link which you provided was really helpful. It solved the my issue. Thanks alot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.