Это моя функция addProduct в моем ProductController:
export const addProduct = async (req, res) => {
try {
const { userId, name, description, price, category, subCategory, sizes, bestseller } = req.body;
const image1 = req.files.image1 && req.files.image1[0];
const image2 = req.files.image2 && req.files.image2[0];
const image3 = req.files.image3 && req.files.image3[0];
const image4 = req.files.image4 && req.files.image4[0];
const images = [image1, image2, image3, image4].filter(item => item !== undefined);
let imagesUrl = await Promise.all(
images.map(async item => {
let result = await cloudinary.uploader.upload(item.path, {
resource_type: "image",
});
return result.secure_url;
})
);
const productData = {
name,
description,
category,
price: Number(price),
subCategory,
bestseller: bestseller === "true",
sizes: JSON.parse(sizes),
image: imagesUrl,
date: Date.now(),
};
// Add product to seller's products array
const seller = await sellerModel.findById(userId);
if (!seller) {
return res.json({ success: false, msg: "Seller not found" });
}
console.log(userId)
seller.products.push(productData);
await seller.save();
res.json({ success: true, msg: "Product Added" });
} catch (err) {
console.log(err);
res.json({ success: false, msg: err.message });
}
};
Код Add.jsx:
import { useState } from 'react'
import { assets } from '../assets/seller_assets/assets'
import axios from 'axios'
import { backendUrl } from '../App'
import { toast } from 'react-toastify'
const Add = () => {
const [image1, setImage1] = useState(false)
const [image2, setImage2] = useState(false)
const [image3, setImage3] = useState(false)
const [image4, setImage4] = useState(false)
const [name, setName] = useState('');
const [description, setDescription] = useState("")
const [price, setPrice] = useState("")
const [category, setCategory] = useState("Men");
const [subCategory, setSubCategory] = useState("Topwear");
const [bestseller, setBestSeller] = useState(false);
const [sizes, setSizes] = useState([])
const onSubmitHandler = async (e) => {
e.preventDefault();
try {
const formData = new FormData();
formData.append("name", name);
formData.append("description", description)
formData.append("price", price)
formData.append("category", category)
formData.append("subCategory", subCategory)
formData.append("bestseller", bestseller)
formData.append("sizes", JSON.stringify(sizes))
image1 && formData.append("image1", image1);
image2 && formData.append("image2", image2);
image3 && formData.append("image3", image3);
image4 && formData.append("image4", image4);
const response = await axios.post(backendUrl+'/api/seller/add',formData,{headers: {"Content-Type": "multipart/form-data"}, withCredentials:true})
if(response.data.success) {
toast.success(response.data.msg);
setName('')
setDescription('')
setPrice('')
setImage1(false)
setImage2(false)
setImage3(false)
setImage4(false)
setBestSeller(false)
}else {
toast.error(response.data.msg)
}
} catch (error) {
console.log(error.message)
toast.error(error.message)
}
}
return (
Upload Image
setImage1(e.target.files[0])} type="file" id="image1" hidden />
setImage2(e.target.files[0])} type="file" id="image2" hidden />
setImage3(e.target.files[0])} type="file" id="image3" hidden />
setImage4(e.target.files[0])} type="file" id="image4" hidden />
Product name
setName(e.target.value)} value={name} className='w-full max-w-[500px] px-3 py-2' type="text" placeholder='Type here' required />
Product description
setDescription(e.target.value)} value={description} className='w-full max-w-[500px] px-3 py-2' type="text" placeholder='Write content here' required />
Product Category
setCategory(e.target.value)} className='w-full px-3 py-2'>
Men
Women
Kids
Foods
Gadgets
Sub Category
setSubCategory(e.target.value)} className='w-full px-3 py-2'>
Topwear
Bottomwear
Winterwear
Main Dish
Breakfast Favourites
Smart Phones
Product Price
setPrice(e.target.value)} value={price} className='w-full px-3 py-2 sm:w-[120px]' type="Number" placeholder='25' />
Product Sizes
setSizes(prev => prev.includes("S")? prev.filter(item => item !== 'S'):[...prev,"S"])}>
S
setSizes(prev => prev.includes("M")? prev.filter(item => item !== 'M'):[...prev,"M"])}>
M
setSizes(prev => prev.includes("L")? prev.filter(item => item !== 'L'):[...prev,"L"])}>
L
setSizes(prev => prev.includes("XL")? prev.filter(item => item !== 'XL'):[...prev,"XL"])}>
XL
setSizes(prev => prev.includes("XXL")? prev.filter(item => item !== 'XXL'):[...prev,"XXL"])}>
XXL
setBestSeller(prev => !prev)} checked={bestseller} type="checkbox" id="bestseller" />
Add to bestseller
ADD
)
}
export default Add
Подробнее здесь: https://stackoverflow.com/questions/793 ... -not-found
Мобильная версия