从node.js表达服务器发送图像路径以响应客户端

时间:2018-02-21 20:35:07

标签: node.js reactjs express

我想构建存储图像的api并将它们发送给客户端应用程序。

图像位于public / images文件夹中的快速应用程序中。

我想将数据obj发送到客户端,其中包含图像路径。

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;

服务器:

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);
});

客户端:

在react应用程序中,我想获取图像路径并进行渲染。

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);

谢谢!

1 个答案:

答案 0 :(得分:1)

您在此处并未提供太多代码,但从我收集到的内容中您已将图像放在public/images目录中,然后您将图像路径发送回客户端并且您希望客户端能够提取图像。

从那以后,我将假设你想要的是Express服务器静态功能。这将允许您提供public/images目录中的静态内容。

The documentation将向您展示如何设置服务静态文件,然后您的前端应该没有问题显示图像。