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

梦想的初衷 提交于 2021-01-28 14:10:04

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/48914987/send-image-path-from-node-js-express-server-to-react-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!