NodeJS 从mongodb获取一个图像到reactjs

ehxuflar  于 2023-03-12  发布在  Node.js
关注(0)|答案(1)|浏览(105)

我是mongodb和nodejs的新手,我保存了一篇文章,文章中有文字和图片到mongodb数据库,我试图获取信息,但图片似乎未定义。
这是后模型

const mongoose = require("mongoose");
const { Schema, model } = mongoose;
const postSchema = new Schema(
  {
    title: String,
    summary: String,
    content: String,
    file: String,
  },
  {
    timestamps: true,
  }
);

const PostModel = model("Post", postSchema);

module.exports = PostModel;

在服务器端,我使用multer中间件传递图像

const multer = require("multer");
const blogStorage = multer.diskStorage({
  destination: (req, file, callback) => {
    callback(null, "./api/postblog");
  },
  filename: (req, file, callback) => {
    callback(null, `${Date.now()}_${file.originalname}`);
  },
});

const postblog = multer({ storage: blogStorage });

app.post("/post", postblog.single("file"), async (req, res) => {
  const { title, summary, content } = req.body;
  const { originalname, path } = req.file;
  const newPath = path;
  const postDoc = await Post.create({
    title,
    summary,
    content,
    file: newPath,
  });
  res.json(postDoc);
});

app.get("/post/:id", async (req, res) => {
  const { id } = req.params;
  const postDoc = await Post.findById(id);
  res.json(postDoc);
});

这是postPage.js页面,我在这里通过id获取帖子

const PostPage = () => {

   const [postInfo, setPostInfo] = useState(null);
   const { userInfo } = useContext(UserContext);
   const { id } = useParams();
   useEffect(() => {
     fetch(`http://localhost:4000/post/${id}`).then((response) => {
       response.json().then((postInfo) => {
         setPostInfo(postInfo);
       });
     });
   }, []);

   if (!postInfo) return "";

  return (
    <div className="post-page">
      <h1>{postInfo.title}</h1>
      <time>{formatISO9075(new Date(postInfo.createdAt))}</time>
      <div className="image">
        <img src={`http://localhost:4000/${postInfo.cover}`} alt="" />
      </div>
      <div
        className="content"
        dangerouslySetInnerHTML={{ __html: postInfo.content }}
      />
    </div>
  );
}

export default PostPage

我得到了除图像之外的所有文件,控制台显示:(未找到)返回首页(未找到)
这是我的博客:
Post collection
这是我的项目结构:project structure
我试了这行代码:应用程序使用(“/postblog”,表达静态(__目录名+“/postblog”));

kse8i1jr

kse8i1jr1#

我用https://cloudinary.com图像后端服务修复了这个问题,
一旦在cloudinary上创建帐户,您将获得一个APIkey和API秘密,首先我下载了带有
npm安装云日志
然后将其包含在server.js中

const cloudinary = require('cloudinary').v2;
  • 我设置了莫特来处理图像上传
  • 并将cloudinary配置为这样存储图像

云计算日志.config({云计算名称:“XXX”,API密钥:“XXXXXXXXXX”,API_机密:“XXXXXXXXXXXXXXXXX”、});
然后我将数据存储在mongodb中,如下所示:

app.post("/post", postblog.single("file"), async (req, res) => {
    const { title, summary, content } = req.body;
    const result = await cloudinary.uploader.upload(req.file.path);
    const postDoc = await Post.create({
      title,
      summary,
      content,
      file: result.secure_url,
    });
    res.json(postDoc);
  });

要在客户端获取图像,您只需要:

const [postInfo, setPostInfo] = useState(null);
  const { id } = useParams();
  useEffect(() => {
    fetch(`http://localhost:4000/post/${id}`).then((response) => {
      response.json().then((postInfo) => {
        setPostInfo(postInfo);
      });
    });
  }, []);

  if (!postInfo) return "";

  return (
    <div className="image">
      <img src={postInfo.} alt="" />
    </div>
  );

相关问题