如何使用 multer 检索和显示存储在服务器端的 reactjs 中的图像,路径存储在数据库中

How to retrieve and display images in reactjs that are stored on the server side using multer and the path is stored in the database

我有类似的 problem.I 将路径存储在名为 Cast 的数据库中,并将图像存储在服务器上。该数据库有两个字段名称和图像。在反应应用程序中,我想显示 image.I 我没有得到图像。 我是 运行 express localhost:5000 和 reactjs localhost:3000。 例如:数据库中的图像具有值 "Anushka.jpg"。在服务器端存储如下:

public
 └─ cast_images 
     └─ Anushka.jpg

app.js 文件(服务器端)

app.use('/login', express.static(path.join(__dirname, '/public')));
app.get('/login',(req,res)=>{
  Cast.find()
  .then(
    cast=>res.json(cast))
    .catch(err => res.status(400).json('Error: ' + err));
});

App.js(前端反应文件):

function App() {
  return (
    <Router>
    <Navbar />
    <br/>
    <Route path="/login" component={Login}/>
    </Router>
  );
}

export default App;

Login.js

import React, { Component } from 'react';
import axios from 'axios';
export default class Login extends Component {
  state={
    casts:[]
  };
  componentDidMount() {
    axios.get('http://localhost:5000/admin/')
      .then(response => {
        this.setState({casts:response.data});
        console.log(response.data);
      })
      .catch((error) => {
        console.log(error);
      })
  }
    render() {
        const actor =this.state.casts.map(actor => {
          return (
             <p>
              <img src="/cast_images/{actor.image}" alt="hello"/>
              <h3>{actor.name}</h3>
            </p>
          );
        });
        return(<p>{actor}</p>);
    }
}

我这里没有提到 React 中的导入 code.This 是 code.Can 的一部分 你请告诉我如何提前获得 image.Thanks。

使用此代码,您可以将 public 文件夹安装到 /login url 路径,我认为这不是您想要的

app.use('/login', express.static(path.join(__dirname, '/public')));

所以应该改成

app.use('/', express.static(path.join(__dirname, '/public')));

而在 React 中,您可以使用 JavaScript template string literal 在字符串中插入变量。

const serverBaseURI = 'http://localhost:5000' // set this to the value of your express server, should be different value for production server
/* .... */
<img src={`${serverBaseURI}/cast_images/${actor.image}`} alt="hello"/>