Commit f4e8de9b authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

product DB에 저장 완료

parent 0ed13690
...@@ -6,8 +6,7 @@ import Signup from './Pages/Signup'; ...@@ -6,8 +6,7 @@ import Signup from './Pages/Signup';
import Product from "./Pages/Product"; import Product from "./Pages/Product";
import ProductsList from "./Pages/ProductsList"; import ProductsList from "./Pages/ProductsList";
import Admin from './Pages/Admin'; import Admin from './Pages/Admin';
// import ProductRegist from './Pages/ProductRegist'; import ProductRegist from './Pages/ProductRegist';
import ProductRegist2 from './Pages/ProductRegist2';
import ShoppingCart from './Pages/ShoppingCart'; import ShoppingCart from './Pages/ShoppingCart';
import Payment from './Pages/Payment'; import Payment from './Pages/Payment';
import Account from './Pages/Account'; import Account from './Pages/Account';
...@@ -16,10 +15,6 @@ import SubNav from './Components/SubNav'; ...@@ -16,10 +15,6 @@ import SubNav from './Components/SubNav';
function App() { function App() {
// const [user,setUser]=useState(null);
// const authenticated =user !=null;
// const login =({id, password}) => setUser(signIn({id,password}));
// const logout=()=>setUser(null);
return ( return (
...@@ -34,8 +29,7 @@ function App() { ...@@ -34,8 +29,7 @@ function App() {
<Route path="/product" component={Product} /> <Route path="/product" component={Product} />
<Route path="/productslist" component={ProductsList} /> <Route path="/productslist" component={ProductsList} />
<Route path="/admin" component={Admin} /> <Route path="/admin" component={Admin} />
{/* <Route path="/regist" component={ProductRegist} /> */} <Route path="/regist" component={ProductRegist} />
<Route path="/regist" component={ProductRegist2} />
<Route path="/shoppingcart" component={ShoppingCart} /> <Route path="/shoppingcart" component={ShoppingCart} />
<Route path="/payment" component={Payment} /> <Route path="/payment" component={Payment} />
<Route path="/account" component={Account} /> <Route path="/account" component={Account} />
...@@ -44,7 +38,6 @@ function App() { ...@@ -44,7 +38,6 @@ function App() {
</Switch> </Switch>
</Router> </Router>
</div> </div>
) )
......
...@@ -5,8 +5,8 @@ import catchErrors from '../utils/catchErrors'; ...@@ -5,8 +5,8 @@ import catchErrors from '../utils/catchErrors';
import { Redirect } from 'react-router-dom'; import { Redirect } from 'react-router-dom';
let color = {} let color = {}
let colors = [] let preColors = []
let addedcolors = [] let colorHtml = []
let list = [] let list = []
function ProductsRegist() { function ProductsRegist() {
...@@ -16,8 +16,8 @@ function ProductsRegist() { ...@@ -16,8 +16,8 @@ function ProductsRegist() {
stock: 0, stock: 0,
main_category: '', main_category: '',
sub_category: [], sub_category: [],
size: [], sizes: [],
color: [], colors: [],
description: '', description: '',
main_image: [], main_image: [],
detail_image: [] detail_image: []
...@@ -61,24 +61,21 @@ function ProductsRegist() { ...@@ -61,24 +61,21 @@ function ProductsRegist() {
} }
function addColor() { function addColor() {
addedcolors.push( preColors.push(color["colors"])
<div>{colors["color"]}</div> colorHtml.push(
<p>{color["colors"]}</p>
) )
if (product[color]) { setProduct({...product, "colors":preColors})
setProduct({ ...product, [color]:Object.values(colors) })
} else {
setProduct({ ...product, "color": Object.values(colors) })
} }
function colorChange(e){
color[e.target.name]= e.target.value
} }
function handleChange(event) { function handleChange(event) {
const { name, value, files } = event.target const { name, value, files } = event.target
if (event.target.name === "sub_category") { if (event.target.name === "sub_category") {
product["sub_category"].push(event.target.value) product["sub_category"].push(event.target.value)
// } else if (event.target.name === "color") {
// colors[event.target.name] = event.target.value
// // console.log(color)
} else if (files) { } else if (files) {
setProduct({ ...product, [name]: files }) setProduct({ ...product, [name]: files })
...@@ -98,14 +95,13 @@ function ProductsRegist() { ...@@ -98,14 +95,13 @@ function ProductsRegist() {
sizes.push(key) sizes.push(key)
} }
} }
product["size"].push(sizes) product["sizes"]=sizes
console.log(product) console.log(product)
const formData = new FormData(); const formData = new FormData();
for (let key in product) { for (let key in product) {
if (key === "main_image" || "detail_image") { if (key === "main_image" ||key === "detail_image") {
formData.append(`${key}`, product[key][0])
console.log(product[key][0]) console.log(product[key][0])
formData.append(key, product[key][0])
} else { } else {
formData.append(key, product[key]) formData.append(key, product[key])
} }
...@@ -168,27 +164,26 @@ function ProductsRegist() { ...@@ -168,27 +164,26 @@ function ProductsRegist() {
</Form.Group> </Form.Group>
<Form.Group> <Form.Group>
<Form.Label>사이즈</Form.Label> <Form.Label>사이즈</Form.Label>
{/* {console.log(checked)} */} <Form.Check type="checkbox" name="sizes" label="Free" value="Free" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="Free" value="Free" onChange={handleCheckBox} /> <Form.Check type="checkbox" name="sizes" label="XL" value="XL" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="XL" value="XL" onChange={handleCheckBox} /> <Form.Check type="checkbox" name="sizes" label="L" value="L" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="L" value="L" onChange={handleCheckBox} /> <Form.Check type="checkbox" name="sizes" label="M" value="M" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="M" value="M" onChange={handleCheckBox} /> <Form.Check type="checkbox" name="sizes" label="S" value="S" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="S" value="S" onChange={handleCheckBox} /> <Form.Check type="checkbox" name="sizes" label="XS" value="XS" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="XS" value="XS" onChange={handleCheckBox} />
</Form.Group> </Form.Group>
<Form.Group> <Form.Group>
<Form.Label>색상</Form.Label> <Form.Label>색상</Form.Label>
<Row> <Row>
<Col md={10}> <Col md={10}>
<Form.Control as="textarea" rows={1} name="color" placeholder="색상" onChange={handleChange} /> <Form.Control as="textarea" rows={1} name="colors" placeholder="색상" onChange={colorChange} />
</Col> </Col>
<Col> <Col>
{/* <Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addColor}>추가</Button> */} <Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addColor}>추가</Button>
</Col> </Col>
</Row> </Row>
{/* {addedcolors.map((element) => element)} */} {colorHtml.map((element) => element)}
</Form.Group> </Form.Group>
<Form.Group controlId="productDescriptionform"> <Form.Group controlId="productDescriptionform">
......
import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Button, Form, Container } from 'react-bootstrap';
import axios from 'axios'
import catchErrors from '../utils/catchErrors';
import { Redirect } from 'react-router-dom';
let color = {}
let colors = []
let addedcolors = []
let list = []
function ProductsRegist() {
const INIT_PRODUCT = {
pro_name: '',
price: 0,
stock: 0,
main_category: '',
sub_category: [],
size: [],
color: [],
description: '',
main_image: [],
detail_image: []
}
const categorys = {
"DRESS": ["LONG DRESS", "SHORT DRESS", "KNIT DRESS", "SHIRT DRESS", "PATTERN DRESS", "BUSTIER DRESS", "TWO-PIECE DRESS"],
"OUTER": ["PADDED JACKET", "JACKET", "JUMPER", "COAT", "FLEECE", "CARDIGAN / VEST"],
"TOP": ["KNIT", "HOODY", "BLOUSE", "SHIRT", "SWEATSHIRT", "LONG SLEEVE SHIRT", "SHORT SLEEVE / SLEEVELESS SHIRT"],
"PANTS": ["JEANS", "SKINNY JEANS", "BANDING PANTS", "WIDE-FIT PANTS", "BOOT-CUT PANTS", "STRAIGHT-FIT PANTS", "SHORTS", "TROUSERS", "LEGGINGS", "JUMPSUIT / OVERALLS"],
"SKIRT": ["LONG SKIRT", "MIDI SKIRT", "MINI SKIRT"],
"TRAINING": [],
"SHOES": ["SNEAKERS / SLIP-ON", "FLAT / LOAFER", "HEEL / PUMP", "BOOTS", "SANDAL / SLIPPER"]
}
const [product, setProduct] = useState(INIT_PRODUCT)
const [categoryNum, setCategoryNum] = useState(0)
const [tag, setTag] = useState(0)
const [error, setError] = useState('')
const [success, setSuccess] = useState(false)
const [checked, setChecked] = useState({ "Free": false, "XL": false, "L": false, "M": false, "S": false, "XS": false })
const mainCategorys = Object.keys(categorys)
const subCategorys = Object.values(categorys)
function addCategory() {
console.log(product)
list.push(
<div>
<span i={tag}>{product["main_category"]} / {product["sub_category"][tag]}</span>
<input type="image" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right align-middle" onClick={deleteCategory} />
</div>)
setTag(tag + 1)
}
function deleteCategory(e) {
const categ = e.target.parentNode
categ.remove()
product["sub_category"].splice(e.target.parentNode.firstElementChild.getAttribute("i"), 1)
console.log(product)
}
function handleCheckBox(e) {
setChecked({ ...checked, [e.target.value]: !checked[`${e.target.value}`] })
}
function addColor() {
addedcolors.push(
<div>{colors["color"]}</div>
)
if (product[color]) {
setProduct({ ...product, [color]:Object.values(colors) })
} else {
setProduct({ ...product, "color": Object.values(colors) })
}
}
function handleChange(event) {
const { name, value, files } = event.target
if (event.target.name === "sub_category") {
product["sub_category"].push(event.target.value)
} else if (event.target.name === "color") {
colors[event.target.name] = event.target.value
// console.log(color)
} else if (files) {
setProduct({ ...product, [name]: files })
} else {
setProduct({ ...product, [name]: value })
}
if (event.target.name === "main_category") {
setCategoryNum(event.target.selectedIndex - 1)
}
}
async function handleSubmit(e) {
e.preventDefault()
const sizes = []
for (let [key, value] of Object.entries(checked)) {
if (value === true) {
sizes.push(key)
}
}
product["size"].push(sizes)
console.log(product)
const formData = new FormData();
for (let key in product) {
if (key === "main_image" ||key === "detail_image") {
console.log(product[key][0])
formData.append(key, product[key][0])
} else {
formData.append(key, product[key])
}
}
try {
const response = axios.post('/api/product/regist', formData)
// setSuccess(true)
console.log(response)
} catch (error) {
catchErrors(error, setError)
}
}
if (success) {
return <Redirect to='/' />
}
return (
<div>
<Container>
<Row className="justify-content-md-center">
<Col md={8} className="border p-1" style={{ background: '#F7F3F3' }}>
<h2 className="text-center mt-5 font-weight-bold">상품등록</h2>
<Form className="p-5" onSubmit={handleSubmit}>
<Form.Group controlId="productNameform">
<Form.Label>상품명</Form.Label>
<Form.Control type="text" name="pro_name" placeholder="상품명" onChange={handleChange} />
</Form.Group>
<Form.Group controlId="productAmountform">
<Form.Label>재고</Form.Label>
<Form.Control type="text" name="stock" placeholder="숫자만 입력해주세요" onChange={handleChange} />
</Form.Group>
<Form.Group controlId="productPriceform">
<Form.Label>가격</Form.Label>
<Form.Control type="text" name="price" placeholder="숫자만 입력해주세요" onChange={handleChange} />
</Form.Group>
<Form.Group>
<Form.Label>분류</Form.Label>
<Row>
<Col md={4}>
<Form.Control as="select" name="main_category" onChange={handleChange}>
<option value="" >상위분류</option>
{mainCategorys.map((main) => (
<option value={main}>{main}</option>
))}
</Form.Control>
</Col>
<Col md={6}>
<Form.Control as="select" name="sub_category" onChange={handleChange}>
<option value="" >하위분류</option>
{subCategorys[categoryNum].map((sub) => (
<option value={sub}>{sub}</option>
))}
</Form.Control>
</Col>
<Col >
<Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addCategory}>추가</Button>
</Col>
</Row>
{list.map((element) => element)}
</Form.Group>
<Form.Group>
<Form.Label>사이즈</Form.Label>
{/* {console.log(checked)} */}
<Form.Check type="checkbox" name="size" label="Free" value="Free" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="XL" value="XL" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="L" value="L" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="M" value="M" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="S" value="S" onChange={handleCheckBox} />
<Form.Check type="checkbox" name="size" label="XS" value="XS" onChange={handleCheckBox} />
</Form.Group>
<Form.Group>
<Form.Label>색상</Form.Label>
<Row>
<Col md={10}>
<Form.Control as="textarea" rows={1} name="color" placeholder="색상" onChange={handleChange} />
</Col>
<Col>
<Button className="float-right" style={{ background: '#91877F', borderColor: '#91877F' }} onClick={addColor}>추가</Button>
</Col>
</Row>
{addedcolors.map((element) => element)}
</Form.Group>
<Form.Group controlId="productDescriptionform">
<Form.Label>상품설명</Form.Label>
<Form.Control as="textarea" name="description" rows={3} placeholder="상품을 설명해주세요" onChange={handleChange} />
</Form.Group>
<Form.Group>
<Form.Label>대표이미지</Form.Label>
<Form.File id="productImageform" name="main_image" onChange={handleChange} />
</Form.Group>
<Form.Group>
<Form.Label>상세이미지</Form.Label>
<Form.File id="productImageform" name="detail_image" onChange={handleChange} />
</Form.Group>
<Button className="float-right" type="submit" style={{ background: '#91877F', borderColor: '#91877F' }}>등록</Button>
</Form>
</Col>
</Row>
</Container>
</div>
)
}
export default ProductsRegist
\ No newline at end of file
...@@ -2,7 +2,7 @@ import Product from "../schemas/Product.js"; ...@@ -2,7 +2,7 @@ import Product from "../schemas/Product.js";
import multer from 'multer'; import multer from 'multer';
const upload = multer({ dest: 'uploads/'}); const upload = multer({ dest: 'uploads/' });
const fileUpload = upload.fields([ const fileUpload = upload.fields([
{ name: 'main_image', maxCount: 1 }, { name: 'main_image', maxCount: 1 },
...@@ -11,15 +11,14 @@ const fileUpload = upload.fields([ ...@@ -11,15 +11,14 @@ const fileUpload = upload.fields([
const regist = async (req, res) => { const regist = async (req, res) => {
console.log('req.body=', req.body) console.log('req.body=', req.body)
const { pro_name, price, stock, main_category, sub_category, description } = req.body const { pro_name, price, stock, main_category, sub_category, colors, sizes, description } = req.body
console.log(req.files) console.log(req.files)
const main_image = req.files['main_image'][0].filename const main_image = req.files['main_image'][0].filename
console.log(main_image) console.log(main_image)
const detail_image = req.files['detail_image'][0].filename const detail_image = req.files['detail_image'][0].filename
// const { main_image, detail_image} = req.files
try { try {
const newProduct = await new Product ({ const newProduct = await new Product({
pro_name, price, stock, main_category, sub_category, description, main_image, detail_image pro_name, price, stock, main_category, sub_category, colors, sizes, description, main_image, detail_image
}).save() }).save()
res.json(newProduct) res.json(newProduct)
} catch (error) { } catch (error) {
...@@ -33,4 +32,4 @@ const getProduct = (req, res) => { ...@@ -33,4 +32,4 @@ const getProduct = (req, res) => {
res.json(req.body) res.json(req.body)
} }
export default { regist, fileUpload , getProduct} export default { regist, fileUpload, getProduct }
\ No newline at end of file \ No newline at end of file
import express from "express"; import express from "express";
// import path from 'path';
// import multer from 'multer';
import productCtrl from '../controllers/product.controller.js'; import productCtrl from '../controllers/product.controller.js';
// import fs from 'fs'
// process.cwd() + '/client/public/image'
const router = express.Router() const router = express.Router()
......
...@@ -20,13 +20,13 @@ const ProductSchema = new mongoose.Schema({ ...@@ -20,13 +20,13 @@ const ProductSchema = new mongoose.Schema({
required: true, required: true,
default: 0 default: 0
}, },
size: { sizes: {
type: Array, type: Array,
// required: true required: true
}, },
color: { colors: {
type: Array, type: Array,
// required: true required: true
}, },
main_category: { main_category: {
type: String, type: String,
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment