Node.js MERN项目Cloudinary图片上传500错误排查求助
MERN项目中Cloudinary图片上传返回500错误
我是Node.js新手,跟着在线教程开发MERN项目已有数周。服务器可正常提交新数据,但使用Cloudinary API将文件保存至Cloudinary时,在Insomnia中测试多次失败,返回500状态码,提示图片无法上传。移除Cloudinary相关代码后提交功能恢复正常,我已配置CLOUDINARY_URL环境变量。
帖子控制器代码
import PostMessage from "../models/postMessage.js"; import asyncHandler from "express-async-handler"; import { fileSizeFormatter } from "../utils/fileUpload.js"; import { v2 as cloudinary } from 'cloudinary'; export const createPost = asyncHandler(async (req, res) => { const {title, tags, content, visibility} = req.body; if (!title || !tags || !content || !visibility) { res.status(400) throw new Error("Please fill in all required fields"); } let fileData = {}; if (req.file) { let uploadedFile; try { uploadedFile = await cloudinary.uploader.upload( req.file.path, {folder: "Tect", resource_type: "image"}, ); } catch (error) { console.error(error); res.status(500); throw new Error("Image could not be uploaded"); } fileData = { fileName: req.file.originalname, filePath: uploadedFile.secure_url, fileType: req.file.mimetype, fileSize: fileSizeFormatter(req.file.size, 2), } } const post = await PostMessage.create({ user: req.user.id, title, tags, content, visibility, image: fileData, }); res.status(201).json(post); });
路由代码
import express from "express"; import { createPost, getPosts, getPost, deletePost, updatePost, getPublicPosts, getPublicStatus, getPublicPost } from '../controllers/posts.js'; import { protect } from "../middleware/auth.js"; import { upload } from "../utils/fileUpload.js"; const router = express.Router(); router.post("/", protect, upload.single("image"), createPost);
文件上传工具代码
import multer from "multer"; /**define file storage */ //the first function enables developers to have control on storing files to disk const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "upload"); }, filename: function (req, file, cb) { cb(null, new Date().toISOString().replace(/:/g, "-") + "-" + file.originalname); } }); //specify the format that can be saved function fileFilter (req, file, cb) { // The function should call `cb` with a boolean // to indicate if the file should be accepted if ( file.mimetype === "image/png" || file.mimetype === "image/jpg" || file.mimetype === "image/jpeg" ) { // To reject this file pass `false`, like so: cb(null, true); } else { // To accept the file pass `true`, like so: cb(null, false); } } //file size format export const fileSizeFormatter = (bytes, decimal) => { if (bytes === 0) { return "0 Bytes"; } const dm = decimal || 2; const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "YB", "ZB"]; const index = Math.floor(Math.log(bytes) / Math.log(1000)); return( parseFloat((bytes / Math.pow(1000, index)).toFixed(dm)) + " " + sizes[index] ); }; export const upload = multer({ storage, fileFilter });
错误日志
Error: Image could not be uploaded at file:///Users/oushinu/Desktop/tect_trial/server/controllers/posts.js:32:19 at asyncUtilWrap (/Users/oushinu/Desktop/tect_trial/server/node_modules/express-async-handler/index.js:3:20) at Layer.handle [as handle_request] (/Users/oushinu/Desktop/tect_trial/server/node_modules/express/lib/router/layer.js:95:5) at next (/Users/oushinu/Desktop/tect_trial/server/node_modules/express/lib/router/route.js:144:13) at Immediate.<anonymous> (/Users/oushinu/Desktop/tect_trial/server/node_modules/multer/lib/make-middleware.js:53:37) at processImmediate (node:internal/timers:468:21)
内容的提问来源于stack exchange,提问作者kkr9551
相关产品推荐
相关产品推荐

