Commit 9af5d81a authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

qwr

parent f4e8de9b
import React from 'react'
import { Card, Button, Container, Row, Col } from 'react-bootstrap';
function CartCard(props) {
return (
<>
{props.cart.map((e) => (
<Card>
<Row className="mx-1">
<Col xs={2} sm={2} className="text-center my-auto">
<input className="" type="checkbox" id="exampleCheck1" />
</Col>
<Col className="text-center">
<Card.Img className="img-fluid" variant="top" src={e.main_image && `/images/${e.main_image}`} style={{ width: '20rem' }} />
</Col>
<Col md={6} className="p-2">
<Card.Body>
<input type="image" name={String(e._id)} alt="삭제버튼" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right" onClick={props.deleteCart} />
<Card.Title className="font-weight-bold mt-3">{e.pro_name}</Card.Title>
<Card.Text>가격: {e.price}</Card.Text>
<Card.Text>옵션: {e.sizes}/{e.colors}</Card.Text>
<Card.Text>수량</Card.Text>
<div>
<input type="image" alt="마이너스" src="https://img.icons8.com/ios-glyphs/20/000000/minus-math.png" className="align-middle" onClick={props.minusNum} />
<input type="text" style={{ width: '30px' }} className="text-center align-middle mx-1" placeholder={e.count} value={e.count} readOnly></input>
<input type="image" alt="플러스" src="https://img.icons8.com/ios-glyphs/20/000000/plus-math.png" className="align-middle" onClick={props.plusNum} />
</div>
</Card.Body>
</Col>
</Row>
</Card>
))
}
</>
)
}
export default CartCard
...@@ -3,24 +3,23 @@ import React, { useState, useEffect, useRef } from 'react'; ...@@ -3,24 +3,23 @@ import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Form, Card, Button } from 'react-bootstrap'; import { Row, Col, Form, Card, Button } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
const INIT_PRODUCT = {
pro_name: '스키니진',
price: 12000,
count:1,
main_category: 'PANTS',
sub_category: ['SKINNY JEANS'],
sizes: [ 'L', 'M'],
colors: ['연청', '진청'],
main_image: "a8f4d63ead77717f940a2b27deb707a6"
}
function Product() { function Product() {
const [product, setProduct] = useState() const [product, setProduct] = useState(INIT_PRODUCT)
const [select, setSelect] = useState({ color: "", size: "" }) const [cart, setCart] = useState(INIT_PRODUCT)
const [cart, setCart] = useState()
const [error, setError] = useState('') const [error, setError] = useState('')
async function getProduct(user){
console.log(user)
try {
const response = await axios.get('/api/product/productone')
setProduct(response.data)
console.log(response.data)
} catch (error) {
catchErrors(error, setError)
}
}
function handleClick(e) { function handleClick(e) {
const box = e.target.parentNode.parentNode const box = e.target.parentNode.parentNode
box.style.display = "none" box.style.display = "none"
...@@ -28,7 +27,8 @@ function Product() { ...@@ -28,7 +27,8 @@ function Product() {
function handleChange(e) { function handleChange(e) {
const { name, value } = e.target const { name, value } = e.target
setSelect({ ...select, [name]: value }) // handleCreate()
setCart({ ...cart, [name]: value })
} }
function listDelete(e) { function listDelete(e) {
...@@ -38,60 +38,55 @@ function Product() { ...@@ -38,60 +38,55 @@ function Product() {
} }
function handleCreate() { function handleCreate() {
console.log("실행", "cart=", cart) console.log("실행", "cart=", product)
if (cart !== undefined) { if (product !== undefined) {
if (cart.color !== "") { if (product.colors !== "" && product.sizes !== "") {
const list = document.getElementById('list') cart.push(
list.style.borderBottom = "1px solid" <div className="d-flex justify-content-between my-2" >
const shopping = document.createElement('div') <p>{product.color} {product.size} </p>
shopping.className = "d-flex justify-content-between my-2" <input name="count" type="number" min="0" max="10" style="width: 40px" onChange={handleChange} />
shopping.innerHTML = `${cart.color} / ${cart.size} <p style="margin-bottom: 0px">{product.price}</p>
<input type="number" min="0" max="10" value="1" style="width: 40px" /> </div>
<p style="margin-bottom: 0px">14,000원</p>` )
const deleteA = document.createElement('a') // const list = document.getElementById('list')
deleteA.innerText = 'X' // list.style.borderBottom = "1px solid"
deleteA.addEventListener('click', listDelete) // const shopping = document.createElement('div')
shopping.appendChild(deleteA) // shopping.className = "d-flex justify-content-between my-2"
list.appendChild(shopping) // shopping.innerHTML = `${product.color} / ${product.size}
// <input type="number" min="0" max="10" value="1" style="width: 40px" />
// <p style="margin-bottom: 0px">14,000원</p>`
// const deleteA = document.createElement('a')
// deleteA.innerText = 'X'
// deleteA.addEventListener('click', listDelete)
// shopping.appendChild(deleteA)
// list.appendChild(shopping)
} }
} }
} }
async function addCart() { async function addCart() {
// color, size, count, productObjectId(productlist에서 props), userId(로컬) 를 보내줌 // color, size, count, productId(productlist에서 props), userId(로컬) 를 보내줌
try { try {
// setError('') // setError('')
const response = await axios.post('/api/addcart', { const response = await axios.put('/api/cart/addcart', {
userId: "jiwon5393", count: cart.count,
productObjectId: "5ff7fd63d41cae4ecce51dd1", productId: "5ffd153b41bada58d8b12d92",
color: "red",
size: "free",
count: "1"
}) })
console.log(response) console.log(response)
}catch(error){ } catch (error) {
// catchErrors(error, setError) catchErrors(error, setError)
} }
alert("상품등록이 완료되었습니다.")
} }
useEffect(() => {
if (Object.keys(select).length == 2) {
setCart({ ...select })
setSelect({})
}
}, [select])
useEffect(() => { // useEffect(() => {
handleCreate() // handleCreate()
getProduct() // }, [product])
}, [cart])
return ( return (
<div> <div>
{/* {getProduct} */} {console.log(cart)}
<style type="text/css"> <style type="text/css">
{` {`
.btn { .btn {
...@@ -115,22 +110,22 @@ function Product() { ...@@ -115,22 +110,22 @@ function Product() {
<Form style={{ borderBottom: "1px solid" }}> <Form style={{ borderBottom: "1px solid" }}>
<Form.Group style={{ borderBottom: "1px solid", paddingBottom: "2rem" }}> <Form.Group style={{ borderBottom: "1px solid", paddingBottom: "2rem" }}>
<Form.Label>색상</Form.Label> <Form.Label>색상</Form.Label>
<Form.Control as="select" className="mb-2" name="color" defaultValue="옵션 선택" onChange={handleChange}> <Form.Control as="select" className="mb-2" name="colors" defaultValue="옵션 선택" onChange={handleChange}>
<option>옵션선택</option> <option>옵션선택</option>
<option>브릭레드(스트랩포함)</option> {product.colors.map((e) => (
<option>베이지(스트랩포함)</option> <option>{e}</option>
<option>블랙(스트랩포함)</option> ))}
</Form.Control> </Form.Control>
<Form.Label>사이즈</Form.Label> <Form.Label>사이즈</Form.Label>
<Form.Control as="select" className="mb-2" name="size" defaultValue="옵션 선택" onChange={handleChange}> <Form.Control as="select" className="mb-2" name="sizes" defaultValue="옵션 선택" onChange={handleChange}>
<option>옵션선택</option> <option>옵션선택</option>
<option>M</option> {product.sizes.map((e) => (
<option>L</option> <option>{e}</option>
<option>XL</option> ))}
<option>FREE</option>
</Form.Control> </Form.Control>
</Form.Group> </Form.Group>
<div id="list"></div> {/* {cart.map((e)=>(<div>{e}</div>
))} */}
<Row className="justify-content-between mx-0 my-3" style={{ width: "100%" }}> <Row className="justify-content-between mx-0 my-3" style={{ width: "100%" }}>
<Col> 금액</Col> <Col> 금액</Col>
<Col className="text-right">14,000</Col> <Col className="text-right">14,000</Col>
......
...@@ -2,10 +2,29 @@ import React, { useState, useEffect, useRef } from 'react'; ...@@ -2,10 +2,29 @@ import React, { useState, useEffect, useRef } from 'react';
import { Redirect } from 'react-router-dom'; import { Redirect } from 'react-router-dom';
import { Card, Button, Container, Row, Col } from 'react-bootstrap'; import { Card, Button, Container, Row, Col } from 'react-bootstrap';
import axios from 'axios'; import axios from 'axios';
import catchErrors from '../utils/catchErrors';
import { isAuthenticated } from '../utils/auth'
import CartCard from '../Components/CartCard';
const INIT_PRODUCT = [{
pro_name: '체크셔츠',
price: 21000,
count: 1,
main_category: 'TOP',
sub_category: ['SHIRT'],
sizes: ['XL', 'L', 'M', 'S'],
colors: ['베이지', '블랙', '카키'],
main_image: 'e46b641ae11e6568c86f689d3dce7748'
}]
function ShoppingCart() { function ShoppingCart() {
const [num, setNum] = useState(0) const [num, setNum] = useState(0)
const [error, setError] = useState('')
const [cart, setCart] = useState(INIT_PRODUCT)
const user = isAuthenticated()
useEffect(() => {
getCart()
}, [user])
function plusNum() { function plusNum() {
setNum(num + 1) setNum(num + 1)
...@@ -19,46 +38,41 @@ function ShoppingCart() { ...@@ -19,46 +38,41 @@ function ShoppingCart() {
} }
} }
function deleteCart() { async function deleteCart(e) {
//장바구니 DB에서 해당 항목 삭제 //장바구니 DB에서 해당 항목 삭제
console.log(e.target.name)
try {
const response = await axios.post('/api/cart/deletecart', { cartId: e.target.name })
console.log(response.data)
} catch (error) {
catchErrors(error, setError)
}
console.log('카트에 담긴 항목을 삭제했습니다.') console.log('카트에 담긴 항목을 삭제했습니다.')
} }
// async function getCart(){ async function getCart() {
// const response = await axios.get('/') // const userId= localStorage.getItem('loginStatus')
// } try {
const response = await axios.get(`/api/cart/showcart/${user}`)
console.log(response.data)
setCart(response.data)
} catch (error) {
catchErrors(error, setError)
}
}
return ( return (
<div> <div>
{/* {getCart} */} {/* {getCart()} */}
{/* {console.log(user)} */}
{/* {console.log(cart)} */}
<Container className="justify-content-center"> <Container className="justify-content-center">
<h3 className="my-5 font-weight-bold text-center">장바구니</h3> <h3 className="my-5 font-weight-bold text-center">장바구니</h3>
<div> <div>
<h4 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h4> <h4 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h4>
<Card> <CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} num={num} />
<Row className="mx-1">
<Col xs={2} sm={2} className="text-center my-auto">
<input className="" type="checkbox" id="exampleCheck1" />
</Col>
<Col className="text-center">
<Card.Img className="img-fluid" variant="top" src="img/asd.jpg" style={{ width: '20rem' }} />
</Col>
<Col md={6} className="p-2">
<Card.Body>
<input type="image" alt="삭제버튼" src="https://img.icons8.com/fluent-systems-regular/24/000000/close-window.png" className="float-right" onClick={deleteCart} />
<Card.Title className="font-weight-bold mt-3">제품명</Card.Title>
<Card.Text>가격</Card.Text>
<Card.Text>옵션</Card.Text>
<Card.Text>수량</Card.Text>
<div>
<input type="image" alt="마이너스" src="https://img.icons8.com/ios-glyphs/20/000000/minus-math.png" className="align-middle" onClick={minusNum} />
<input type="text" style={{ width: '30px' }} className="text-center align-middle mx-1" placeholder="1" value={num} readOnly></input>
<input type="image" alt="플러스" src="https://img.icons8.com/ios-glyphs/20/000000/plus-math.png" className="align-middle" onClick={plusNum} />
</div>
</Card.Body>
</Col>
</Row>
</Card>
</div> </div>
<div className="p-5 m-5" style={{ background: '#F7F3F3' }}> <div className="p-5 m-5" style={{ background: '#F7F3F3' }}>
<ul className="pl-0" style={{ listStyle: 'none' }}> <ul className="pl-0" style={{ listStyle: 'none' }}>
......
...@@ -20,13 +20,14 @@ app.use(cors()) ...@@ -20,13 +20,14 @@ app.use(cors())
app.use(express.static(path.join(process.cwd(), 'dist'))) app.use(express.static(path.join(process.cwd(), 'dist')))
// app.use(bodyParser.urlencoded({ extended: true })) // app.use(bodyParser.urlencoded({ extended: true }))
app.use('/images', express.static('uploads/'))
// app.use('/', indexRouter); // app.use('/', indexRouter);
app.use('/', kakaopayRoutes) app.use('/', kakaopayRoutes)
app.use('/api/users',userRouter) app.use('/api/users',userRouter)
app.use('/api/auth',authRouter) app.use('/api/auth',authRouter)
app.use('/api/product', productRouter) app.use('/api/product', productRouter)
app.use('/api/addcart', cartRouter) app.use('/api/cart', cartRouter)
app.listen(config.port, () => { app.listen(config.port, () => {
console.info('Server started on port %s.', config.port) console.info('Server started on port %s.', config.port)
......
import Cart from "../schemas/Cart.js"; import Cart from "../schemas/Cart.js";
import Product from '../schemas/Product.js'
const cart = async (req, res) => {
const { userId, productObjectId, color, size, count } = req.body
// console.log('req.body=', req.body)
// const {userId, productObjectId, }
// const { user, pro_name, price, main_image } = req.body
// color, size, count, productObjectId(productlist에서 props), userId(로컬)
try {
const product = await Product.find({ _id: productObjectId })
if (product) {
// console.log(product)
const { pro_name, price, main_image } = product[0]
const products = { productObjectId, color, size, count, pro_name, price, main_image }
// console.log(products)
const newCart = await new Cart({
userId, products
}).save()
console.log(newCart)
res.json(newCart)
} const addcart = async (req, res) => {
// const newCart = await new Cart({ console.log(req.body)
// user, pro_name, price, stock, main_category, sub_category, main_image const { count, productId } = req.body
// }).save() try {
// const asdf = await Cart.find({ user }) const newProduct = { count, product: productId }
// console.log(newCart) await Cart.findOneAndUpdate(
// res.json(newCart) { _id: cart._id },
{ $addToSet: { products: newProduct } }
)
res.json(newCart)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
res.status(500).send('죄송합니다. 다시 입력해 주십시오.') res.status(500).send('죄송합니다. 다시 입력해 주십시오.')
} }
}
const showcart = async (req, res) => {
// const {userId} = req.body
console.log(req.cart)
try {
const cart = await Cart.findOne({ user: userId }).populate({
path: 'products.product',
model: 'Product'
})
res.status(200).json(cart.products)
// try {
// const user = await } catch (error) {
// User.findById(id) console.log(error)
// if (!user) { res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
// console.log(error) }
// res.status(404).send('사용자를 찾을 수 없습니다')
// }
// req.profile = user
// next()
// } catch (error) {
// console.log(error)
// res.status(500).send('사용자 아이디 실패')
// }
} }
export default { cart } const deletecart = async (req, res) => {
\ No newline at end of file console.log(req.body)
const { cartId } = req.body
try {
await Cart.remove({ _id: cartId })
res.send("삭제완료")
// res.json()
} catch (error) {
console.log(error)
res.status(500).send('해당 카트를 삭제하지 못했습니다.')
}
}
const userById = async (req, res, next, id) => {
try {
const cart = await Cart.findOne({ userId: id })
if (!cart) {
res.status(404).send("사용자를 찾을 수 없습니다.")
}
req.cart = cart
next()
} catch (error) {
res.status(500).send("사용자 아이디 검색 실패")
}
}
export default { addcart, showcart, deletecart, userById }
\ No newline at end of file
...@@ -4,27 +4,28 @@ import bcrypt from 'bcryptjs' ...@@ -4,27 +4,28 @@ import bcrypt from 'bcryptjs'
const signup = async (req, res) => { const signup = async (req, res) => {
console.log(req.body) console.log(req.body)
const { name, number1, number2, id, password, tel } = req.body const { name, number1, number2, id, password, tel } = req.body
try { try {
if(!isLength(password,{min:8, max:15})){ if (!isLength(password, { min: 8, max: 15 })) {
return res.status(422).send('비밀번호는 8-15자리로 입력해주세요.') return res.status(422).send('비밀번호는 8-15자리로 입력해주세요.')
} }
const user=await User.findOne({id}) const user = await User.findOne({ id })
if(user){ if (user) {
return res.status(422).send(`${id}가 이미 사용중입니다.`) return res.status(422).send(`${id}가 이미 사용중입니다.`)
} }
const hash=await bcrypt.hash(password,10)
const newUser = await new User ({ const hash = await bcrypt.hash(password, 10)
const newUser = await new User({
name, name,
number1, number1,
number2, number2,
id, id,
password:hash, password: hash,
tel, tel,
}).save() }).save()
await new Cart({ user: newUser._id }).save()
console.log(newUser) console.log(newUser)
res.json(newUser) res.json(newUser)
......
...@@ -4,8 +4,16 @@ import cartCtrl from '../controllers/cart.controller.js'; ...@@ -4,8 +4,16 @@ import cartCtrl from '../controllers/cart.controller.js';
const router = express.Router() const router = express.Router()
router.route('/') router.route('/addcart')
.post(cartCtrl.cart) .put(cartCtrl.addcart)
// .get() // .get()
router.route('/showcart/:userId')
.get(cartCtrl.showcart)
router.param('userId', cartCtrl.userById)
router.route('/deletecart')
.post(cartCtrl.deletecart)
export default router export default router
\ No newline at end of file
import mongoose from 'mongoose' import mongoose from 'mongoose'
const { String, Number, Array, ObjectId } = mongoose.Schema.Types const { String, Number, Array, ObjectId } = mongoose.Schema.Types
const productschema = new mongoose.Schema ({
pro_name: {
type: String,
required: true
},
price:{
type: Number,
required: true
},
main_image: {
type: String,
required: true
},
color:{
type: String,
required: true
},
size:{
type: String,
required: true
},
productObjectId: {
type: ObjectId,
required: true
}
})
const CartSchema = new mongoose.Schema({ const CartSchema = new mongoose.Schema({
userId: { userId: {
type: String, type: ObjectId,
// required: true ref: 'User'
}, },
products : { products: {
type: [productschema], type: [
required: true {
count: {
type: Number,
default: 1
},
product: {
type: ObjectId,
ref: 'Product'
}
}
]
} }
}, {
timestamps: true
}) })
export default mongoose.models.Cart || mongoose.model('Cart', CartSchema) export default mongoose.models.Cart || mongoose.model('Cart', CartSchema)
\ No newline at end of file
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