REST API - Can't fetch Post image in front end

Can't get this image when I fetch and want to display it in the front end

exports.createPost = async (req, res, next) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        const error = new Error("Validation failed, entered data is incorrect.");
        error.statusCode = 422;
        throw error;
      }
      if (!req.file) {
        const error = new Error("No image provided.");
        error.statusCode = 422;
        throw error;
      }
      const imageUrl = req.file.path;
      const title = req.body.title;
      const content = req.body.content;
      const post = new Post({
        title: title,
        content: content,
        imageUrl: imageUrl,
        creator: req.userId,
      });
      try {
        await post.save();
        const user = await User.findById(req.userId);
        user.posts.push(post);
        await user.save();
        io.getIO().emit("posts", {
          action: "create",
          post: { ...post._doc, creator: { _id: req.userId, name: user.name } },
        });
        res.status(201).json({
          message: "Post created successfully!",
          post: post,
          creator: { _id: user._id, name: user.name },
        });
      } catch (err) {
        if (!err.statusCode) {
          err.statusCode = 500;
        }
        next(err);
      }
    };

This is my update post code Image path stored absolutely fine facing problem to get an image in frontend stored image in local works also path completely well stores in MongoDB...

exports.updatePost = async (req, res, next) => {
  const postId = req.params.postId;
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    const error = new Error("Validation failed, entered data is incorrect.");
    error.statusCode = 422;
    throw error;
  }
  const title = req.body.title;
  const content = req.body.content;
  let imageUrl = req.body.image;
  if (req.file) {
    imageUrl = req.file.path;
  }
  if (!imageUrl) {
    const error = new Error("No file picked.");
    error.statusCode = 422;
    throw error;
  }
  try {
    const post = await Post.findById(postId).populate("creator");
    if (!post) {
      const error = new Error("Could not find post.");
      error.statusCode = 404;
      throw error;
    }
    if (post.creator._id.toString() !== req.userId) {
      const error = new Error("Not authorized!");
      error.statusCode = 403;
      throw error;
    }
    if (imageUrl !== post.imageUrl) {
      clearImage(post.imageUrl);
    }
    post.title = title;
    post.imageUrl = imageUrl;
    post.content = content;
    const result = await post.save();
    io.getIO().emit("posts", {
      action: "update",
      post: result,
    });
    res.status(200).json({ message: "Post updated!", post: result });
  } catch (err) {
    if (!err.statusCode) {
      err.statusCode = 500;
    }
    next(err);
  }
};

Help me out suggestions are most welcome... Image path stored absolutely fine facing problem to get an image in frontend stored image in local works also path completely well stores in MongoDB...

2 answers

  • answered 2021-09-27 14:09 Shadow111

    Might be facing this error because of path problem you store path but might be wrong once try below code to store path...

    imageUrl = req.file.path.replace("\\", "/");
    

    In both when you insert image and when you update image as well...

  • answered 2021-09-27 14:15 Smit Gajera

    exports.createPost = async (req, res, next) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        const error = new Error("Validation failed, entered data is incorrect.");
        error.statusCode = 422;
        throw error;
      }
      if (!req.file) {
        const error = new Error("No image provided.");
        error.statusCode = 422;
        throw error;
      }
      const imageUrl = req.file.path.replace("\\", "/");
      const title = req.body.title;
      const content = req.body.content;
      const post = new Post({
        title: title,
        content: content,
        imageUrl: imageUrl,
        creator: req.userId,
      });
      try {
        await post.save();
        const user = await User.findById(req.userId);
        user.posts.push(post);
        await user.save();
        io.getIO().emit("posts", {
          action: "create",
          post: { ...post._doc, creator: { _id: req.userId, name: user.name } },
        });
        res.status(201).json({
          message: "Post created successfully!",
          post: post,
          creator: { _id: user._id, name: user.name },
        });
      } catch (err) {
        if (!err.statusCode) {
          err.statusCode = 500;
        }
        next(err);
      }
    };
    

    It works for me, thanks to you done from both create and update image path

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum