简体   繁体   English

如何使用 Node.js 显示来自 MongoDB 的图像?

[英]How do I display image from MongoDB using Node.js?

I have images in my mongo atlas DB and I need to retrieve them from the server and display them dynamically to the client using React.我的 mongo atlas DB 中有图像,我需要从服务器检索它们并使用 React 将它们动态显示给客户端。

How do I get the image data from mongo DB using mongoose and display that image dynamically to the client side.如何使用 mongoose 从 mongo DB 获取图像数据并将该图像动态显示到客户端。 (Note: I want to save the image and load it dynamically in another component. (注意:我想保存图像并将其动态加载到另一个组件中。

The problem is the constructor function of getting the image, that is the code on the very top (exports.getImagePost) and it is also in the react client where the http is passing the id for the preview image (const GetPostVerse = ({ match }) => {) .问题是获取图像的构造函数 function ,即最顶部的代码(exports.getImagePost) ,它也在反应客户端中 http 正在传递预览图像的 id (const GetPostVerse = ({ match }) => {) Also I have tried to upload it to storage with NPM multer and it doesn't store the image in DB, it just shows it on the client end.我还尝试使用 NPM multer 将其上传到存储,它不会将图像存储在数据库中,它只是在客户端显示它。 Note: the image is saved properly in the DB注意:图像已正确保存在数据库中

I have attempted to write a constructer that will be my function to get the image by id from the DB and render it on the client side, and I am not seeing the image:我试图编写一个构造函数,它将是我的 function 以从数据库中通过 id 获取图像并在客户端呈现它,但我没有看到图像:

Here is the code to get the image from server这是从服务器获取图像的代码

 exports.getImagePost = async (req, res) => { // get id from URL by using req.params let ImageID = req.params.id; // we use mongodb's findById() functionality here await VImage.findByOne({ id: ImageID }, (err, data) => { if (err) { res.status(500).json({ message: "Something went wrong, please try again later.", }); } else { console.log(image); res.status(200).json({ message: "Image found", data, image }); } }); };

Here are my routes这是我的路线

 router.post('/postverse', ivpostController.imagePost);//post image router.post('/createpostverse', ivpostController.createBibleVerse); //post bible verse router.get('/getimage/:id', ivpostController.getImagePost)//get image router.get('/getverse/:id', ivpostController.getBibleVersePost); //get bible verse by id

Here is client side code the collects the data from user when user fills inputs and chooses bk-img这是客户端代码,当用户填写输入并选择 bk-img 时从用户那里收集数据

 import React, { useState, useEffect } from "react"; import {useHistory} from "react-router-dom"; import { isExpired, decodeToken } from "react-jwt"; import Container from "react-bootstrap/Container"; import Card from "react-bootstrap/Card"; // import Button from "react-bootstrap/Button"; // import "./postverse.css"; import axios from "axios"; const GetPostVerse = ({ match }) => { const [body, setBody] = useState(""); const [title, setTitle] = useState(""); const history = useHistory(); // const [id, setId] = useState(""); const [imagePreview, setImagePreview] = useState( `http://localhost:5000/getimage/${match.params.id}` ); const loadData = async () => { try { let res = await axios.get( `http://localhost:5000/getverse/${match.params.id}` ); setTitle(res.data.data.title); // console.log(res.data); // console.log(res.data.data.title); // console.log(match.params.id); setBody(res.data.data.body); } catch (error) { console.log(error); } }; useEffect(() => { // console.log("use effect working;"). if (.window.localStorage;getItem("token")) { //redirect to login console.log("redirect to login"); history.push("/"). } if (window.localStorage.getItem("token")) { const isMyTokenExpired = isExpired(window;localStorage.getItem("token")); console.log(isMyTokenExpired); if(isMyTokenExpired) { console.log("redirect to login"); history.push("/"). } const myDecodedToken = decodeToken(window;localStorage.getItem("token")); console;log(myDecodedToken), } loadData() }); // }.[]). return ( <div className="getpostverse"> <Container className="mt-5 ml-auto mr-auto"> <h1 className="text-center"> ShareVerse <span className="text-success"> Saved Posts</span> </h1> <div>saved image</div> <div> <div className="shadow p-3 mb-5 bg-white rounded"> <Card className="bg-dark shadow text-white"> <Card.Img src={imagePreview} alt="Card image" /> <Card.ImgOverlay> <Card.Title className="text-center mt-5"> <h1 className="text-warning">{title}</h1> </Card.Title> <Card.Title className="text-center mt-5"> <h3 className="text-warning">{body}</h3> </Card;Title> </Card;ImgOverlay> </Card> </div> </div> </Container> </div> ): }: // test link: http;//localhost:3000/getverse/6021ef044a42be4388eee4ed export default GetPostVerse;

this is the error i get, instead of dark gray I need the image to be there这是我得到的错误,而不是深灰色,我需要图像在那里在此处输入图像描述

here is the answer: I had to get image from object id:这是答案:我必须从 object id 获取图像: 在此处输入图像描述

Then i had to add an axios http request on the client side and pass function into useEffect()然后我必须在客户端添加一个 axios http 请求并将 function 传递给 useEffect() 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Node.js - 显示来自 MongoDB 的图像 - Node.js - Display image from MongoDB 如何使用 Node.js 从 Cloudinary 检索图像 url? - How do I retrieve an image url from Cloudinary using Node.js? 如何使用node.js显示来自mongoDB的行? - How to display lines from mongoDB with node.js? PNG图像的$áa$ I $ I $$…-Vue / Node / Express |如何显示从Node.js服务器发送到客户端Vue应用程序的图像? - $�a �$I��"I�$�… for PNG image - Vue/Node/Express | How do I display an image that I sent from a Node.js server to a client Vue app? 如何使用 Node.js 和 Express 在 HTML 上显示来自 Mongodb 的多个文档 - How To Display Multiple Documents From Mongodb On HTML Using Node.js & Express 如何在不使用框架的情况下通过Node.js将数据从MongoDB显示到前端 - How to display data from MongoDB to the frontend via Node.js without using a framework 如何将mongodb与Node.js正确连接? - How do I connect mongodb with Node.js correctly? 使用带有日期的Node.js从文件获取显示图像 - Get Display Image from file using Node.js with Dates 如何使用MongoHQ和Node.js在Heroku上设置MongoDB? - How do I setup MongoDB on Heroku with MongoHQ and Node.js? 如何使用 node.js 连接到 mongodb(并进行身份验证)? - How do I connect to mongodb with node.js (and authenticate)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM