【问题标题】: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如何使用multer在reactjs中检索和显示存储在服务器端的图像,并且路径存储在数据库中
【发布时间】:2020-06-03 02:15:02
【问题描述】:

我遇到了类似的问题。我将路径存储在名为 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 代码中的导入。这是代码的一部分。你能告诉我如何获取图像。提前谢谢。

【问题讨论】:

  • 有了这个app.use('/login', ...,你将/loigin映射到你的静态文件路径,试试app.use('/', ...
  • 嘿。非常感谢您的回复。我尝试了你所说的,但我仍然无法访问图像,我注意到的一件新事情是,在 中,actor.image 的值没有被替换为值存储在数据库中。
  • 当我将图像名称硬编码为 我能够在 localhost:5000(我的快递正在运行的地方)上获取图像,但不能在 localhost :3000(我的反应应用程序正在运行)
  • 然后你必须在你的路径前加上你的实际服务器基础 url。同样在反应中,您可以使用“js模板字符串文字”将变量值放在字符串中,而不是引号和美元符号&lt;img src={`${serverBaseURI}/cast_images/${actor.image}`} alt="hello"/&gt;

标签: reactjs mongodb image express multer


【解决方案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"/>

【讨论】:

  • 但它不应该在 localhost:3000 上工作吗?我只是有点好奇为什么它不能在 localhost:3000 上工作
  • 因为您的图像是从 http 服务器而不是文件系统提供的。该 http 服务器由localhost:5000 上的 express 管理。您已指示 express 使用 express.static 从文件系统中获取文件。
猜你喜欢
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
  • 2014-12-10
  • 2020-02-12
  • 2018-10-27
相关资源
最近更新 更多