NodeJS 创建后处理控制器适用于图像(文件),但不适用于没有图像的情况

d8tt03nd  于 2022-12-18  发布在  Node.js
关注(0)|答案(1)|浏览(111)

我的控制器Post无法创建帖子。
我认为主要的问题是条件“if(req.file!== null)”在我不上传文件时仍然起作用(图片字段是准确的,因为图片应该是一个文件)
如果有人已经有了这个问题,我很想听听!提前谢谢你。
我将在这里向您展示我的代码:
js(仅限创建发布)

module.exports.createPost = async (req, res) => {
  let fileName;

  if (req.file !== null) {
    try {
      if (
        req.file.mimetype != "image/jpg" &&
        req.file.mimetype != "image/png" &&
        req.file.mimetype != "image/jpeg"
      )
        throw Error("invalid file");
  
      if (req.file.size > 500000) throw Error("max size");
    } catch (err) {
      const errors = uploadErrors(err);
      return res.status(201).json({ errors });
    }
    fileName = req.body.posterId + Date.now() + ".jpg";

    try {
    await sharp(req.file.buffer)
    .resize({ width: 150, height: 150 }) 
    .toFile(`${__dirname}/../client/public/uploads/posts/${fileName}`
    );
  } catch (err) {
    res.status(400).send(err);
  }
  }

  const newPost = new postModel({
    posterId: req.body.posterId,
    message: req.body.message,
    picture: req.file !== null ? "./uploads/posts/" + fileName : "",
    video: req.body.video,
    likers: [],
    comments: [],
  });

  try {
    const post = await newPost.save();
    return res.status(201).json(post);
  } catch (err) {
    return res.status(400).send(err);
  }
};

邮政路线:

const router = require('express').Router();
const postController = require('../controllers/post.controller');
const multer = require("multer");
const upload = multer();

router.get('/', postController.readPost);
router.post('/', upload.single("file"), postController.createPost);

模型后:

const mongoose = require('mongoose');

const PostSchema = new mongoose.Schema(
  {
    posterId: {
      type: String,
      required: true
    },
    message: {
      type: String,
      trim: true,
      maxlength: 500,
    },
    picture: {
      type: String,
    },
    video: {
      type: String,
    },
    likers: {
      type: [String],
      // required: true,
    },
    comments: {
      type: [
        {
          commenterId:String,
          commenterPseudo: String,
          text: String,
          timestamp: Number,
        }
      ],
      // required: true,
    },
  },
  {
    timestamps: true,
  }
);

module.exports = mongoose.model('post', PostSchema);

lb3vh1jj

lb3vh1jj1#

这是因为当你不上传图片时,req.file将是未定义,而不是
尝试更改您的代码:

if (req.file !== null) {

改为:

if (req.file) {

相关问题