![](/img/trans.png)
[英]Post request error in expess.js TypeError: Cannot read property 'fullName' of undefined
[英]Express.js application error: Cannot read properties of undefined (reading 'transfer-encoding'
我正在使用 express 和 MongoDB 開發博客應用程序 API。
我正在嘗試為每篇博客文章添加一個帖子圖片。 作為新手,我遇到了這個問題。
我得到了這個錯誤:無法讀取未定義的屬性(讀取“傳輸編碼”
這里是post controller code代碼:
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);
});
我也有const multer = require("multer");
在 controller 的頂部。
在我嘗試添加此上傳圖片功能之前,創建帖子 function 工作正常。
這一行:“createPost = asyncHandler(async (res, req)
”
你把req
和res
放在錯誤的順序
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.