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

时间:2020-06-01 16:59:04

标签: reactjs mongodb image express multer

我遇到类似的问题。我将路径存储在名为Cast的数据库中,并将图像存储在服务器上。该数据库具有两个字段名称和图像。在React应用中,我想显示图像。我没有得到图像。 我在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;

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

1 个答案:

答案 0 :(得分:1)

使用此代码,您将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"/>