Search code examples
javascriptnode.jsexpresscloudinary

cloudinary is returning an empty object when trying to upload an image + the image isn't being uploaded (express server)


i'm trying to implement an image upload using cloudinary in an express server and everything is working just fine but the result of the cloudinary uploader is an empty object for some reason and of course the image isn't being uploaded.

upload route:

const router = require('express').Router() ;

const cloudinary = require('cloudinary');
const auth = require('../middleware/auth');
const authAdmin = require('../middleware/authAdmin');

//cloudinary configs ...
cloudinary.config({
    cloud_name : process.env.CLOUD_NAME, 
    api_key: process.env.CLOUD_API_KEY,
    api_secret: process.env.CLOUD_API_SECRET
});


// upload image...
router.post('/upload',auth , authAdmin, (req, res) =>{
    try {
        if(!req.files || Object.keys(req.files).length === 0)
            return res.status(400).json({msg: 'No files were uploaded.'});
        
        const file = req.files.file;
        if(file.size > 1024*1024) {
            removeTmp(file.tempFilePath);
            return res.status(400).json({msg: "Size too large"});
        }

        if(file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png'){
            removeTmp(file.tempFilePath);
            return res.status(400).json({msg: "File format is incorrect."});
        }

        console.log(req.files) ;
        cloudinary.v2.uploader.upload(file.tempFilePath, {folder: "test"}, async(err, result)=>{
            if(err) throw err;

            removeTmp(file.tempFilePath)

            res.json({public_id: result.public_id, url: result.secure_url})
        })
    } catch (err) {
        return res.status(500).json({msg: err.message});
    }
});



const removeTmp = (path) =>{
    fs.unlink(path, err=>{
        if(err) throw err;
    })
};



module.exports = router ; 

in the .env file :

CLOUD_API_KEY= API_KEY_HERE
CLOUD_NAME: CLOUD_NAME_HERE
CLOUD_API_SECRET= API_SECRET_HERE

of course i have my actual information in the file but i can't publish them here for security reasons.

when i try this route in postman i get an empty object as you see in the following pics :

the postman result i'm getting when calling this route

this is the output of the console log statements i added to the code...

i did try the following :

  • looking up online to see if my code is wrong , and i couldn't find my problem.
  • check if the references to my api keys and secret and name are correct.
  • checked and tried multiple ways to write these things in the .env file and looked it up and found that it is correct and there is no problem with it.

Solution

  • i was able to solve this problem with the help of @Aleksandar 's comment.

    after returning err instead of err.message i got the error which is "you must provide the cloud name".

    after that i was able to fix the error easily by providing the correct cloud name.