Error: Cannot read properties of undefined (reading ‘path’) when uploading files with Multer and Cloudinary

I’ve been following a tutorial from YouTube and encountered an error when trying to test my API with Thunder Client. Despite my debugging efforts, I haven’t been able to resolve it. I’d appreciate some help!

I’m getting the following error when testing my API:TypeError: Cannot read properties of undefined (reading 'path')

cloudinaryConfig.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { v2 as cloudinary } from 'cloudinary';
const connectCloudinary = async () => {
cloudinary.config({
cloud_name: process.env.CLOUDINARY_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_SECRET_KEY,
});
};
export default connectCloudinary;
</code>
<code>import { v2 as cloudinary } from 'cloudinary'; const connectCloudinary = async () => { cloudinary.config({ cloud_name: process.env.CLOUDINARY_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_SECRET_KEY, }); }; export default connectCloudinary; </code>
import { v2 as cloudinary } from 'cloudinary';

const connectCloudinary = async () => {
    cloudinary.config({
        cloud_name: process.env.CLOUDINARY_NAME,
        api_key: process.env.CLOUDINARY_API_KEY,
        api_secret: process.env.CLOUDINARY_SECRET_KEY,
    });
};
export default connectCloudinary;

multer.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import multer from 'multer';
import path from 'path';
const storage = multer.diskStorage({
destination: function (req, file, callback) {
// Specify the directory for storing uploaded files
callback(null, path.resolve('./uploads'));
},
filename: function (req, file, callback) {
console.log("The file name is: ", file);
// Use the original file name or customize it
callback(null, new Date().toISOString() + file.originalname);
},
});
const upload = multer({ storage });
export default upload;
</code>
<code>import multer from 'multer'; import path from 'path'; const storage = multer.diskStorage({ destination: function (req, file, callback) { // Specify the directory for storing uploaded files callback(null, path.resolve('./uploads')); }, filename: function (req, file, callback) { console.log("The file name is: ", file); // Use the original file name or customize it callback(null, new Date().toISOString() + file.originalname); }, }); const upload = multer({ storage }); export default upload; </code>
import multer from 'multer';
import path from 'path';

const storage = multer.diskStorage({
    destination: function (req, file, callback) {
        // Specify the directory for storing uploaded files
        callback(null, path.resolve('./uploads'));
    },
    filename: function (req, file, callback) {
        console.log("The file name is: ", file);
        // Use the original file name or customize it
        callback(null, new Date().toISOString() + file.originalname);
    },
});

const upload = multer({ storage });

export default upload;

adminRoute.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import express from 'express';
import { addDoctor } from '../controllers/adminController.js';
import upload from '../middlewares/multer.js';
const adminRouter = express.Router();
adminRouter.post('/add-doctor', upload.single('image'), addDoctor);
export default adminRouter;
</code>
<code>import express from 'express'; import { addDoctor } from '../controllers/adminController.js'; import upload from '../middlewares/multer.js'; const adminRouter = express.Router(); adminRouter.post('/add-doctor', upload.single('image'), addDoctor); export default adminRouter; </code>
import express from 'express';
import { addDoctor } from '../controllers/adminController.js';
import upload from '../middlewares/multer.js';

const adminRouter = express.Router();

adminRouter.post('/add-doctor', upload.single('image'), addDoctor);

export default adminRouter;

adminController.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import validator from 'validator';
import bcrypt from 'bcrypt';
import { v2 as cloudinary } from 'cloudinary';
import doctorModel from '../models/doctorModel.js';
import path from 'path';
const addDoctor = async (req, res) => {
try {
const { name, email, password, speciality, degree, experience, about, fees, address } = req.body;
const imageFile = req.file;
if (!name || !email || !password || !speciality || !degree || !experience || !about || !fees || !address) {
return res.json({ success: false, message: 'Missing some details' });
}
if (!validator.isEmail(email)) {
return res.json({ success: false, message: 'Please enter a valid Email' });
}
if (password.length < 8) {
return res.json({ success: false, message: 'Please, provide a strong password' });
}
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
const imageUpload = await cloudinary.uploader.upload(imageFile.path, { resource_type: 'image' });
const imageUrl = imageUpload.secure_url;
const doctorData = {
name,
email,
image: imageUrl,
password: hashedPassword,
speciality,
degree,
experience,
about,
fees,
address: JSON.parse(address),
date: Date.now(),
};
const newDoctor = new doctorModel(doctorData);
await newDoctor.save();
res.json({ success: true, message: 'Doctor added' });
} catch (error) {
console.log(error);
res.json({ success: false, message: error.message });
}
};
export { addDoctor };
</code>
<code>import validator from 'validator'; import bcrypt from 'bcrypt'; import { v2 as cloudinary } from 'cloudinary'; import doctorModel from '../models/doctorModel.js'; import path from 'path'; const addDoctor = async (req, res) => { try { const { name, email, password, speciality, degree, experience, about, fees, address } = req.body; const imageFile = req.file; if (!name || !email || !password || !speciality || !degree || !experience || !about || !fees || !address) { return res.json({ success: false, message: 'Missing some details' }); } if (!validator.isEmail(email)) { return res.json({ success: false, message: 'Please enter a valid Email' }); } if (password.length < 8) { return res.json({ success: false, message: 'Please, provide a strong password' }); } const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(password, salt); const imageUpload = await cloudinary.uploader.upload(imageFile.path, { resource_type: 'image' }); const imageUrl = imageUpload.secure_url; const doctorData = { name, email, image: imageUrl, password: hashedPassword, speciality, degree, experience, about, fees, address: JSON.parse(address), date: Date.now(), }; const newDoctor = new doctorModel(doctorData); await newDoctor.save(); res.json({ success: true, message: 'Doctor added' }); } catch (error) { console.log(error); res.json({ success: false, message: error.message }); } }; export { addDoctor }; </code>
import validator from 'validator';
import bcrypt from 'bcrypt';
import { v2 as cloudinary } from 'cloudinary';
import doctorModel from '../models/doctorModel.js';
import path from 'path';

const addDoctor = async (req, res) => {
    try {
        const { name, email, password, speciality, degree, experience, about, fees, address } = req.body;
        const imageFile = req.file;

        if (!name || !email || !password || !speciality || !degree || !experience || !about || !fees || !address) {
            return res.json({ success: false, message: 'Missing some details' });
        }

        if (!validator.isEmail(email)) {
            return res.json({ success: false, message: 'Please enter a valid Email' });
        }

        if (password.length < 8) {
            return res.json({ success: false, message: 'Please, provide a strong password' });
        }

        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt);

        const imageUpload = await cloudinary.uploader.upload(imageFile.path, { resource_type: 'image' });
        const imageUrl = imageUpload.secure_url;

        const doctorData = {
            name,
            email,
            image: imageUrl,
            password: hashedPassword,
            speciality,
            degree,
            experience,
            about,
            fees,
            address: JSON.parse(address),
            date: Date.now(),
        };

        const newDoctor = new doctorModel(doctorData);
        await newDoctor.save();

        res.json({ success: true, message: 'Doctor added' });
    } catch (error) {
        console.log(error);
        res.json({ success: false, message: error.message });
    }
};

export { addDoctor };

When I send a POST request with a file (key: image) and form data, the doctor should be added successfully, and the image should be uploaded to Cloudinary.

I’m using Thunder Client to test the API.
The file upload key is named image.
What could be causing the path to be undefined in req.file?

New contributor

Kabanga David is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Error: Cannot read properties of undefined (reading ‘path’) when uploading files with Multer and Cloudinary

I’ve been following a tutorial from YouTube and encountered an error when trying to test my API with Thunder Client. Despite my debugging efforts, I haven’t been able to resolve it. I’d appreciate some help!

I’m getting the following error when testing my API:TypeError: Cannot read properties of undefined (reading 'path')

cloudinaryConfig.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { v2 as cloudinary } from 'cloudinary';
const connectCloudinary = async () => {
cloudinary.config({
cloud_name: process.env.CLOUDINARY_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_SECRET_KEY,
});
};
export default connectCloudinary;
</code>
<code>import { v2 as cloudinary } from 'cloudinary'; const connectCloudinary = async () => { cloudinary.config({ cloud_name: process.env.CLOUDINARY_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_SECRET_KEY, }); }; export default connectCloudinary; </code>
import { v2 as cloudinary } from 'cloudinary';

const connectCloudinary = async () => {
    cloudinary.config({
        cloud_name: process.env.CLOUDINARY_NAME,
        api_key: process.env.CLOUDINARY_API_KEY,
        api_secret: process.env.CLOUDINARY_SECRET_KEY,
    });
};
export default connectCloudinary;

multer.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import multer from 'multer';
import path from 'path';
const storage = multer.diskStorage({
destination: function (req, file, callback) {
// Specify the directory for storing uploaded files
callback(null, path.resolve('./uploads'));
},
filename: function (req, file, callback) {
console.log("The file name is: ", file);
// Use the original file name or customize it
callback(null, new Date().toISOString() + file.originalname);
},
});
const upload = multer({ storage });
export default upload;
</code>
<code>import multer from 'multer'; import path from 'path'; const storage = multer.diskStorage({ destination: function (req, file, callback) { // Specify the directory for storing uploaded files callback(null, path.resolve('./uploads')); }, filename: function (req, file, callback) { console.log("The file name is: ", file); // Use the original file name or customize it callback(null, new Date().toISOString() + file.originalname); }, }); const upload = multer({ storage }); export default upload; </code>
import multer from 'multer';
import path from 'path';

const storage = multer.diskStorage({
    destination: function (req, file, callback) {
        // Specify the directory for storing uploaded files
        callback(null, path.resolve('./uploads'));
    },
    filename: function (req, file, callback) {
        console.log("The file name is: ", file);
        // Use the original file name or customize it
        callback(null, new Date().toISOString() + file.originalname);
    },
});

const upload = multer({ storage });

export default upload;

adminRoute.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import express from 'express';
import { addDoctor } from '../controllers/adminController.js';
import upload from '../middlewares/multer.js';
const adminRouter = express.Router();
adminRouter.post('/add-doctor', upload.single('image'), addDoctor);
export default adminRouter;
</code>
<code>import express from 'express'; import { addDoctor } from '../controllers/adminController.js'; import upload from '../middlewares/multer.js'; const adminRouter = express.Router(); adminRouter.post('/add-doctor', upload.single('image'), addDoctor); export default adminRouter; </code>
import express from 'express';
import { addDoctor } from '../controllers/adminController.js';
import upload from '../middlewares/multer.js';

const adminRouter = express.Router();

adminRouter.post('/add-doctor', upload.single('image'), addDoctor);

export default adminRouter;

adminController.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import validator from 'validator';
import bcrypt from 'bcrypt';
import { v2 as cloudinary } from 'cloudinary';
import doctorModel from '../models/doctorModel.js';
import path from 'path';
const addDoctor = async (req, res) => {
try {
const { name, email, password, speciality, degree, experience, about, fees, address } = req.body;
const imageFile = req.file;
if (!name || !email || !password || !speciality || !degree || !experience || !about || !fees || !address) {
return res.json({ success: false, message: 'Missing some details' });
}
if (!validator.isEmail(email)) {
return res.json({ success: false, message: 'Please enter a valid Email' });
}
if (password.length < 8) {
return res.json({ success: false, message: 'Please, provide a strong password' });
}
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
const imageUpload = await cloudinary.uploader.upload(imageFile.path, { resource_type: 'image' });
const imageUrl = imageUpload.secure_url;
const doctorData = {
name,
email,
image: imageUrl,
password: hashedPassword,
speciality,
degree,
experience,
about,
fees,
address: JSON.parse(address),
date: Date.now(),
};
const newDoctor = new doctorModel(doctorData);
await newDoctor.save();
res.json({ success: true, message: 'Doctor added' });
} catch (error) {
console.log(error);
res.json({ success: false, message: error.message });
}
};
export { addDoctor };
</code>
<code>import validator from 'validator'; import bcrypt from 'bcrypt'; import { v2 as cloudinary } from 'cloudinary'; import doctorModel from '../models/doctorModel.js'; import path from 'path'; const addDoctor = async (req, res) => { try { const { name, email, password, speciality, degree, experience, about, fees, address } = req.body; const imageFile = req.file; if (!name || !email || !password || !speciality || !degree || !experience || !about || !fees || !address) { return res.json({ success: false, message: 'Missing some details' }); } if (!validator.isEmail(email)) { return res.json({ success: false, message: 'Please enter a valid Email' }); } if (password.length < 8) { return res.json({ success: false, message: 'Please, provide a strong password' }); } const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(password, salt); const imageUpload = await cloudinary.uploader.upload(imageFile.path, { resource_type: 'image' }); const imageUrl = imageUpload.secure_url; const doctorData = { name, email, image: imageUrl, password: hashedPassword, speciality, degree, experience, about, fees, address: JSON.parse(address), date: Date.now(), }; const newDoctor = new doctorModel(doctorData); await newDoctor.save(); res.json({ success: true, message: 'Doctor added' }); } catch (error) { console.log(error); res.json({ success: false, message: error.message }); } }; export { addDoctor }; </code>
import validator from 'validator';
import bcrypt from 'bcrypt';
import { v2 as cloudinary } from 'cloudinary';
import doctorModel from '../models/doctorModel.js';
import path from 'path';

const addDoctor = async (req, res) => {
    try {
        const { name, email, password, speciality, degree, experience, about, fees, address } = req.body;
        const imageFile = req.file;

        if (!name || !email || !password || !speciality || !degree || !experience || !about || !fees || !address) {
            return res.json({ success: false, message: 'Missing some details' });
        }

        if (!validator.isEmail(email)) {
            return res.json({ success: false, message: 'Please enter a valid Email' });
        }

        if (password.length < 8) {
            return res.json({ success: false, message: 'Please, provide a strong password' });
        }

        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt);

        const imageUpload = await cloudinary.uploader.upload(imageFile.path, { resource_type: 'image' });
        const imageUrl = imageUpload.secure_url;

        const doctorData = {
            name,
            email,
            image: imageUrl,
            password: hashedPassword,
            speciality,
            degree,
            experience,
            about,
            fees,
            address: JSON.parse(address),
            date: Date.now(),
        };

        const newDoctor = new doctorModel(doctorData);
        await newDoctor.save();

        res.json({ success: true, message: 'Doctor added' });
    } catch (error) {
        console.log(error);
        res.json({ success: false, message: error.message });
    }
};

export { addDoctor };

When I send a POST request with a file (key: image) and form data, the doctor should be added successfully, and the image should be uploaded to Cloudinary.

I’m using Thunder Client to test the API.
The file upload key is named image.
What could be causing the path to be undefined in req.file?

New contributor

Kabanga David is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật