I am having issues with uploading images still, I get 200 when I upload my forms without attaching images but got no response when I attached Image.
I'm trying to upload image in MongoDB using multer and react but I'm unable to post it. I have three inputs in by form i.e title, description and image. If I try to post title and content only it is successfully being posted.
Here is my code:
const postSchema = new Schema(
{
title: { type: String, required: true, trim: true },
description: { type: String, required: true, trim: true },
image: {
type: Object,
},
My file upload config:
import { v2 as cloudinary } from "cloudinary";
import { CloudinaryStorage } from "multer-storage-cloudinary";
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_SECRET_KEY,
});
const storage = new CloudinaryStorage({
cloudinary,
allowedFormats: ["jpg", "png", "jpeg"],
params: {
folder: "leo-blog",
format: "jpg",
transformation: [{ width: 500, height: 500, crop: "limit" }],
},
});
export default storage;
My post route
import { Router } from "express";
import multer from "multer";
import postController from "../../controller/posts/postController.js";
import storage from "../../utilities/fileUpload.js";
const upload = multer({ storage });
const postRouter = Router();
postRouter
.post("/posts/create", upload.single("image", {name:'image'}), postController.createPost)
.get("/posts", postController.fetchAllPosts)
.get("/posts/:postId", postController.fetchOnePost)
.put("/posts/:postId", postController.updatePost)
.delete("/posts/:postId", postController.deletePost);
export default postRouter;
My create post logic
const postController = {
createPost: handler(async (req, res) => {
console.log(req.file);
try {
const { description, title } = req.body;
const postCreated = await Post.create({
description,
title,
image: req?.file,
});
res.json(postCreated);
} catch (error) {
res
.status(500)
.json({ message: "Internal Server Error", error: error.message });
}
}),
//Other logic
Here is what my postman looked like on every trial, I have also tried it from React and I got the same issue.
I would appreciate if you can help point out my error, something like this has also kept me hanging on one of my projects.
Here is the git
I should get the file object on submit but I got no response
