通过从Node.js后端检索,在React前端显示像google drive这样的图像
要通过从Nodejs后端检索来显示React网页中文件夹内的图像。将指向的路径存储在数据库中。然后,在服务器端代码中检索它,并以json格式返回。 然后,您可以像这样在浏览器中输入 http://localhost:300/retrieve_picture 要查看如下所示的json输出:通过从Node.js后端检索,在React前端显示像google drive这样的图像,node.js,reactjs,Node.js,Reactjs,要通过从Nodejs后端检索来显示React网页中文件夹内的图像。将指向的路径存储在数据库中。然后,在服务器端代码中检索它,并以json格式返回。 然后,您可以像这样在浏览器中输入 http://localhost:300/retrieve_picture 要查看如下所示的json输出: [ { "picture":/path-to-picture/pic.jpg", " image-title":"My lovely pictur
[
{
"picture":/path-to-picture/pic.jpg",
" image-title":"My lovely picture",
}
]
在react代码中,可以调用后端API来显示图像
反应代码:
constructor(props){
super(props);
this.state={
photo:[ ]
}
}
//Making call to the API
fetch("http://localhost:300/retrieve_picture",
{
"method": " GET",
"Content-Type":" application/json",
}
).
then (res=>res.json())
/*Updating the state to render json output into the empty array*/
.then (data=>
this.setState({
photo:data
})
)
.catch(err=>console.log(err);
//You now render it like this
render(){
return (
<div>
{
this.state.photo.map(p=>
<div>
<h3>{p.image-title}</h3>
<img src={`http://localhost:300${t.picture} }\>
</div>
)
<\div>
)
}
建造师(道具){
超级(道具);
这个州={
照片:[]
}
}
//调用API
取回(“http://localhost:300/retrieve_picture",
{
“方法”:“获取”,
“内容类型”:“应用程序/json”,
}
).
然后(res=>res.json())
/*更新状态以将json输出呈现到空数组中*/
。然后(数据=>
这是我的国家({
照片:数据
})
)
.catch(err=>console.log(err);
//现在可以这样渲染它
render(){
返回(
{
this.state.photo.map(p=>
{p.image-title}
)
)
}