尝试将 mongodb 文档上传到我的集合时为什么会收到 204 HTTP?

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

我正在向我的 api 端点发送一个 post 请求,

import { upload } from "../controllers/imageUpload.js";

(router.post("/:userId/add-product", checkAuth, upload.single('image'),  createProduct)
)

imageUpload.js :
import multer from "multer";
import path from "path";

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, 'public/images');
    },
    filename: (req, file, cb) => {
      const ext = path.extname(file.originalname);
      const filename = `${file.fieldname}-${Date.now()}${ext}`;
      cb(null, filename);
    },
  });
  
  export const upload = multer({ storage });
  console.log(upload);

,为了以登录用户身份更新我在 Mongo Db 中的产品集合。

身份验证有效,但问题是我的产品集合没有得到更新,只有我的(用户集合)users.products 数组(该数组只包含 createdProduct 的 _id)得到更新,

这里是控制器函数 createProduct :


export const createProduct = async (req, res, next) => {
try {
  const id = req.params.userId;
  const user = await User.findById(id);
  console.log('user found');
  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }

  const form = formidable({ multiples: true });

  const [fields, files] = await new Promise((resolve, reject) => {
    form.parse(req, (err, fields, files) => {
      if (err) {
        reject(err);
      } else {
        resolve([fields, files]);
      }
    });
  });

  const image = files.image;
  const imagePath = path.join(__dirname, '..', 'public', 'images', image.name);
  console.log(image)
  // Move the image file to the public/images directory
  await fs.rename(image.path, imagePath, (err) => {
    if (err) {
      console.error(err);
      return next(new HttpError('Failed to upload image', 500));
    }

    const createdProduct = new Product({
      title: fields.title,
      description: fields.description,
      price: fields.price,
      image: {
        filename: image.name,
        size: image.size,
        format: image.type,
        location: `/images/${image.name}`,
      },
      location: fields.location,
      condition: fields.condition,
      category: fields.category,
      seller: fields.seller,
    });
   console.log(createdProduct.title)
    try {
      createdProduct.save();
      user.products.push(createdProduct._id);
      user.save();
      // console.log(createdProduct);
      // JWT token signing
      const token = jwt.sign({ userId: user.id }, 'supersecretkey', {
        expiresIn: '1h',
      });
      res.status(201).json({ product: createdProduct, token });
    } catch (err) {
      const error = new HttpError(
        'Creating product failed, please try again.',
        500
      );
      next(error);
    }
  });
} catch (error) {
  console.error(error);
  res.status(404).json({ message: error.message });
}
};

Formidable 始终有效并根据我更新产品系列的请求解析我的数据。当我尝试对产品实施图像字段时出现问题。 我在后端收到的唯一信息是 204 HTTP,没有错误。

这里是发送请求到 createProduct 端点的前端 formik:

 const addProductFormik = useFormik({
    initialValues: {
      title: '',
      description: '',
      price: '',
      image: null,
      location: '',
      condition: '',
      category: '',
      seller : seller,
    },
    validationSchema: schema,
    onSubmit: async (values) => {
      try {
        const formData = new FormData();
        formData.append('title', values.title);
        formData.append('description', values.description);
        formData.append('price', values.price);
        formData.append('image', values.image);
        formData.append('location', values.location);
        formData.append('condition', values.condition);
        formData.append('category', values.category);
        formData.append('seller', values.seller);

        const url = `http://localhost:3005/product/${user._id}/add-product`;
        console.log(formData.get('image'));
    
        const config = {
          headers: {
            "Authorization": "Bearer " + token,
            'Content-Type': 'multipart/form-data',
          },
        };
      
        const response = await axios.post(url, formData, config);
        console.log(response.data);
        const newProduct = response.data.product;
        console.log(newProduct);
        // dispatch(createProduct(newProduct));
      } catch (error) {
        console.error(error?.response?.data ?? error.message)
      }
    },
  });

当我控制台登录 newProduct 时,控制台中没有任何显示,前端控制台中也没有错误。

供参考,这里是产品架构:

import mongoose from "mongoose";
const Schema = mongoose.Schema;

const ProductSchema = new Schema({
  title: {
    type: String,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  image: {
    filename: {
      type: String,
      required: true
    },
    size: {
      type: Number
    },
    format:{
      type: String
    },
    location:{
      type:String
    }
  },
  location: {
    type: String,
    required: true,
  },
  
  condition: {
    type: String,
    required: true,
  },
  category: {
    type: String,
    required: true,
    enum: ["Cars", "Electronics", "Clothing", "Furniture", "Other"],
  },
  seller: {
    type: Schema.Types.ObjectId,
    ref: "User",
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

const Product = mongoose.model("Product", ProductSchema);
export default Product;

我怀疑这是图像的解析错误,因为之前解析的一切都很好,或者 multer 配置中的一些错误。任何能发现错误的人都会感激不尽。谢谢。

node.js reactjs mongodb multer formik
© www.soinside.com 2019 - 2024. All rights reserved.