首页 > 解决方案 > 如何使用multer在reactjs中检索和显示存储在服务器端的图像,并且路径存储在数据库中

问题描述

我有类似的问题。我将路径存储在名为 Cast 的数据库中,并将图像存储在服务器上。数据库有两个字段名称和图像。在反应应用程序中,我想显示图像。我没有得到图像。我在 localhost:5000 上运行 express,在 localhost:3000 上运行 reactjs。例如:数据库中的图像具有值“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;

登录.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 代码中的导入。这是代码的一部分。你能告诉我如何获取图像。提前谢谢。

标签: reactjsmongodbimageexpressmulter

解决方案


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

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

所以应该改成

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

在 React 中,您可以使用 JavaScript模板字符串文字在字符串中插入变量。

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"/>

推荐阅读