reactjs - 如何使用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 代码中的导入。这是代码的一部分。你能告诉我如何获取图像。提前谢谢。
解决方案
使用此代码,您将public
文件夹安装到/login
url 路径,我认为这不是您想要的
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"/>
推荐阅读
- gmail-api - 是否可以使用 User.messages.list 同步收件箱消息?
- java - 传递了错误的参数。爪哇
- javascript - 如何让 if/else 语句在函数内部工作
- sql-server - 授予创建数据库的访问权限,但不授予对现有数据库的访问权限
- kubernetes - 可以从 metrics-server 获取哪些指标用于 Horizontal Pod Autoscaling
- ios - Swift:使用 NSNotification 更新 Button.setTitle 和当前 UIPageView
- python - 如何使用列表操作字典并插入另一个字典
- html - 使用VBA从Excel中的网页中提取表格
- java - 当我们在类名中使用“iOS”作为单词时,我们应该将“i”大写吗?
- html - 在登录表单中制作下面的导航链接