1
votes

I want to upload pictures to cloudinary and store the link on my mongoDB database. I want to use multer to upload the file but for some reason I am getting req.file undefined in the uploadPost function which is in post.js. This is the user.js routes file where I declared the route '/create-post'.

const express = require('express');

const router = express.Router();

const {newpost,uploadPost}=require('../controllers/post')  
const { isAuth } = require('../middleware/auth');

const multer=require('multer');


const storage=multer.diskStorage({});


const fileFilter=(req,file,cb)=>{
    if(file.mimetype.startsWith('image')){
        cb(null,true);
    }else{
        cb('invalid image file!',false);
    }
}

const uploads=multer({storage,fileFilter})

router.post('/create-post',isAuth,newpost,uploads.single('post'),uploadPost);

module.exports = router;

Please ignore isAuth. It is just a jsonwebtoken authorization function.

This is post.js.It has two functions, newpost middleware and uploadPost.

const PostModel=require('../models/Posts');
const jwt=require('jsonwebtoken');
const UserModel=require('../models/Users')
const cloudinary=require('../helper/imageUploader')
exports.newpost=async(req,res,next)=>{
   try {
   const token = req.headers.authorization.split(' ')[1];
   const decode = jwt.verify(token, process.env.JWT_SECRET);
   const user_id = await decode.userId;

   const Newuser=await UserModel.findById(user_id);
       if(!Newuser){
          return res.json({success:false,message:"No User found"});
       }

       let newpost=new PostModel({
         user_id:user_id,
        display_name:req.body.display_name,
         image:'' 
       });
    console.log(newpost);
    await newpost.save();
    req.newpost=newpost;   
    next();
   } catch (error) {
      res.json({success:false,message:"New post not created"})
   }
        
 };
exports.uploadPost=async(req,res)=>{
          const {newpost}=req;
          console.log(newpost);
          console.log(req.file);//This is coming undefined(Used postman to upload)
      }

This is the console's output:-enter image description here

Also, I am correctly using postman and I am sure there is no error there. Please Help! I am stuck here. Thank You.

Are you sure you are sending the request body in an form-data format?Ikdemm
@Ikdemm Yes, I am sending the image in form-data only.Rahul Thakur