封面图像路径未定义

问题描述 投票:0回答:1

发送 POST 请求时。在邮递员中,我收到错误 coverImage 路径未定义“无法读取未定义的属性(读取'路径')”, 当我控制台记录 req.files 时,我只在数组中获取头像 obj,但它应该包含 coverImage。

enter image description here enter image description here

这里是 user.controller.js 代码

import { asyncHandler } from '../utils/asyncHandler.js';
import { ApiError } from '../utils/ApiError.js';
import { User } from '../models/user.model.js';
import {uploadToCloudinary} from '../utils/cloudinary.js';
import { ApiResponse } from '../utils/ApiResponse.js';

const registerUser = asyncHandler(async (req, res) => {
    // get the user data from the request body
    // validate the user data not empty
    // check if the user already exists
    // check for img, and avatar
    // upload to cloudinary, avatar
    // create user object -creat entry in db
    // remove password and token from the object
    // check for user creation
    // return the response

    const {fullName, email, userName, password} = req.body
    console.log(fullName, email, userName, password)

    if(!fullName || !email || !userName || !password){
        throw new ApiError(400, 'Please fill all the fields')
    }

    const existedUser = await User.findOne({
        $or: [
            {email},
            {userName}
        ]
    })

    if(existedUser){
        throw new ApiError(409, 'User already exists')
    }

    console.log(req.files)
    const avatarLocalPath = req.files?.avatar[0]?.path
    const coverImageLocalPath = req.files?.coverImage[0]?.path || "" //Error: Cannot read property '0' of undefined
    if(!avatarLocalPath){
        throw new ApiError(400, 'Please provide an avatar')
    }

    const avatar = await uploadToCloudinary(avatarLocalPath)
    const coverImage = await uploadToCloudinary(coverImageLocalPath)

    if(!avatar){
        throw new ApiError(500, 'Error uploading avatar')
    }

    const user = await User.create({
        fullName,
        email,
        userName: userName.toLowerCase(),
        password,
        avatar: avatar.url,
        coverImage: coverImage?.url || ""
    })
    const createdUser = await User.findById(user._id).select('-password -refreshToken')

    if(!createdUser){
        throw new ApiError(500, 'Something went wrong while registering the user')
    }

    return res.status(201).json(new ApiResponse(201, createdUser, 'User registered successfully'))
    
})

export { registerUser }

multer.middleware.js

import multer from "multer"

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./public/temp")
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})

export const upload = multer({ 
    storage, 
})

用户.routes.js

import { Router } from "express"; 
import { registerUser } from "../controllers/user.controller.js";
import {upload} from "../middlewares/multer.middleware.js";

const router = Router();

router.route('/register').post(
    upload.fields([
        {name: 'avatar', maxCount: 1},
        {name: 'coverImage', maxCount: 2}
    ]),
    registerUser
    )

export default router;

和 cloudinary.js

import {v2 as cloudinary} from 'cloudinary'
import fs from 'fs'

// Configure cloudinary
cloudinary.config({ 
  cloud_name: process.env.COULDINARY_CLOUD_NAME, 
  api_key: process.env.COULDINARY_API_KEY,
  api_secret: process.env.COULDINARY_API_SECRET
});

const uploadToCloudinary = async (localFilePath) => {
    try{
        if(!localFilePath) {
        throw new Error('No file received')
        }
        // Upload file to cloudinary
        const response = await cloudinary.uploader.upload(localFilePath, { resource_type: "auto" })

        //file uploaded successfully
        console.log(response.url);
        return response;

    } catch(error) {
        fs.unlinkSync(localFilePath) // Delete the locally saved temp. file if it was not uploaded to cloudinary
        return null;
    }
        
}


export { uploadToCloudinary }

javascript node.js runtime-error backend multer
1个回答
0
投票

首先确保 req.files?.coverImage 是一个列表,然后将其替换为现有代码文件中的以下代码行。

const coverImageLocalPath = req.files?.coverImage?.[0]?.path || "";
© www.soinside.com 2019 - 2024. All rights reserved.