Currently, I am developing a blogging app API using express and MongoDB.
In my project, I want to include an image for each blog post. However, as someone who is new to express, I encountered a specific issue that has been puzzling me.
The error message I received reads: Cannot read properties of undefined (reading 'transfer-encoding'
Below is the code snippet from the post controller:
const asyncHandler = require("express-async-handler");
const imageModel = require("../models/imageModel");
const User = require("../models/userModel");
const Post = require("../models/postModel");
// storage
const Storage = multer.diskStorage({
destination: "storage",
filename: (res, req, file, cb) => {
cb(null, Date.now() + file.originalname);
},
});
const upload = multer({
storage: Storage,
}).single("img");
// @desc Create a new post
// @route POST /api/posts/
// @access Private
const createPost = asyncHandler(async (res, req) => {
let img;
upload(req, res, async function (err) {
if (err) {
res.status(400);
throw new Error("Error uploading images.");
}
const newImage = await new imageModel({
img: {
data: req.file.filename,
contentType: "image/png",
},
});
newImage.save().then(console.log("Successfully uploaded"));
img = newImage;
});
console.log(img);
const { title, description, categories, nacCompatible, downloadURL } =
req.body;
if (!title || !description || !categories || !downloadURL) {
res.status(400);
throw new Error("Please add all the required fields.");
}
// Get user using the id in the JWT
const user = await User.findById(req.user.id);
if (!user) {
res.status(401);
throw new Error("User not found");
}
const post = await Post.create({
title,
description,
img,
categories,
nacCompatible,
downloadURL,
user: req.user._id,
status: "new",
});
res.status(201).json(post);
});
I also included
const multer = require("multer");
at the top of the controller.
Prior to implementing the image upload feature, the create post function worked without any issues.