【问题标题】:Image is not showing up on frontend after fetching from mongoDB从 mongoDB 获取后,图像未显示在前端
【发布时间】:2021-12-03 21:34:43
【问题描述】:

您好,我正在处理我的 fyp,我是反应 js 和节点 js 的新手,当我上传图像时,我已成功将图像存储在 mongoDB 数据库中,在我的情况下,图像存储在本地存储中存储在名为“uploads”的文件夹中,图像的名称存储在数据库中,当我尝试通过提供本地存储图像的路径 + 存储在数据库中的名称来获取图像时,它不显示任何图像,而是显示损坏的图像。图像的名称存储在变量名称“profileImage”中,并且正在从数据库中正确检索。不知道这里有人指导我的问题是什么。附上输出和代码截图供参考。

前端代码和获取 api

import React, { useEffect,useState } from 'react';
import {useHistory} from "react-router-dom";
import axios from 'axios'


const About = () =>{
const history = useHistory();

const [id, setID] = useState('');
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
const [work, setWork] = useState('');
const [profileimage, setPimage] = useState('');


const CallAbtPageA=()=>{
  axios.get('/about')
  .then((res) => {
    setID(res.data.id);
    setName(res.data.name);
    setEmail(res.data.email);
    setPhone(res.data.phone);
    setWork(res.data.work);
    setPimage(res.data.photo);
  })
  .catch((error) => {
    console.log(error);
    history.push('/login');
  });

}


useEffect(()=>{
  CallAbtPageA();
});

  return(
  <div>
    <form method="GET"  encType="multipart/form-data">
      <div> <h1 style={{display:'inline',color:'black'}}>ID:</h1>    <p style={{display:'inline',fontSize:"35px"}}>{name}</p> </div>
      <div> <h1 style={{display:'inline',color:'black'}}>Name:</h1>    <p style={{display:'inline',fontSize:"35px"}}>{name}</p> </div>
      <div> <h1 style={{display:'inline',color:'black'}}>EMAIL:</h1>    <p style={{display:'inline',fontSize:"35px"}}>{email}</p> </div>
      <div> <h1 style={{display:'inline',color:'black'}}>PHONE:</h1>    <p style={{display:'inline',fontSize:"35px"}}>{phone}</p> </div>
      <div> <h1 style={{display:'inline',color:'black'}}>WORK:</h1>    <p style={{display:'inline',fontSize:"35px"}}>{work}</p> </div>
    </form>
    <div> <h1 style={{display:'inline',color:'black'}}>PROFILE PIC:</h1> <img src = {`./uploads/${profileimage}`}  /> </div>
  </div>
)
 }

 export default About;``` 



[![Screenshot of output][1]][1]

  [1]: https://i.stack.imgur.com/oWtw4.png

[![Screenshot of Response is in below link][2]][2]

  [2]: https://i.stack.imgur.com/pVPfi.png

【问题讨论】:

  • 我相信像这样使用useEffect会导致死循环,在依赖列表中放一个空数组还需要说明profileimage是绝对链接还是相对链接
  • profileimage 是一个变量,我在其中从数据库中获取图像的名称
  • 你能告诉我如何让它工作
  • 添加响应截图,你会在谷歌浏览器网络标签中找到它
  • 我附上了回复的截图,请看一下并指导我如何以正确的方式做到这一点

标签: node.js reactjs express multer


【解决方案1】:

你的 api 后端是什么?在那里找不到图片,因为您可能没有提供静态图片资源。

【讨论】:

  • 你能详细说明一下吗?
【解决方案2】:

这是因为您的上传文件夹未公开访问。因此,要解决此问题,您必须在 Express 中将文件夹作为静态文件夹提供服务。

在 nodejs 中试试这个:

app.use('/uploads',express.static('uploads'))

【讨论】:

  • 我试过了,但结果一样
猜你喜欢
  • 2018-05-29
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多