Search code examples
node.jsexpressmulter

req.file is undefined when I use multer to upload post


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. One more thing to add, when I am not using newpost middleware and instead of that using uploadPost for same purpose, it does return req.file but now I am not getting display_name from req.body and newpost.save() doesn't work.

exports.uploadPost=async(req,res)=>{
            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);
                    console.log(req.file);
                    await newpost.save();   
                    req.newpost=newpost;
                } catch (error) {
                   res.json({success:false,message:"New post not created"})
                }
                const {newpost}=req;
                console.log(newpost);
}

Here is the postman window:-enter image description hereenter image description here Here is the console's output for this case:-enter image description here Also,Here is the model schema:-

const mongoose=require('mongoose');
const Schema=mongoose.Schema;
const ObjectId=Schema.ObjectId;

const PostSchema=new Schema({
    user_id:{
        type:ObjectId,
        required:true
    },
    display_name:{
        type:String,
        required:true
    },
    image:{
        type:String
    },
    timestamp:{
        type:String,
        default:Date.now()
    }
});

const PostModel=mongoose.model('Post',PostSchema);

module.exports=PostModel;

Please Help! I am stuck here. Thank You.


Solution

  • Anyways, I solved the problem by making separate routes to create newpost and upload post but I still don't know why req.file is undefined when I use newpost as a middleware.