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';
import { Row, Col, Form, Card, Button } from 'react-bootstrap';
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() {
const [product, setProduct] = useState()
const [select, setSelect] = useState({ color: "", size: "" })
const [cart, setCart] = useState()
const [product, setProduct] = useState(INIT_PRODUCT)
const [cart, setCart] = useState(INIT_PRODUCT)
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) {
const box = e.target.parentNode.parentNode
box.style.display = "none"
......@@ -28,7 +27,8 @@ function Product() {
function handleChange(e) {
const { name, value } = e.target
setSelect({ ...select, [name]: value })
// handleCreate()
setCart({ ...cart, [name]: value })
}
function listDelete(e) {
......@@ -38,60 +38,55 @@ function Product() {
}
function handleCreate() {
console.log("실행", "cart=", cart)
if (cart !== undefined) {
if (cart.color !== "") {
const list = document.getElementById('list')
list.style.borderBottom = "1px solid"
const shopping = document.createElement('div')
shopping.className = "d-flex justify-content-between my-2"
shopping.innerHTML = `${cart.color} / ${cart.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)
console.log("실행", "cart=", product)
if (product !== undefined) {
if (product.colors !== "" && product.sizes !== "") {
cart.push(
<div className="d-flex justify-content-between my-2" >
<p>{product.color} {product.size} </p>
<input name="count" type="number" min="0" max="10" style="width: 40px" onChange={handleChange} />
<p style="margin-bottom: 0px">{product.price}</p>
</div>
)
// const list = document.getElementById('list')
// list.style.borderBottom = "1px solid"
// const shopping = document.createElement('div')
// shopping.className = "d-flex justify-content-between my-2"
// 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() {
// color, size, count, productObjectId(productlist에서 props), userId(로컬) 를 보내줌
// color, size, count, productId(productlist에서 props), userId(로컬) 를 보내줌
try {
// setError('')
const response = await axios.post('/api/addcart', {
userId: "jiwon5393",
productObjectId: "5ff7fd63d41cae4ecce51dd1",
color: "red",
size: "free",
count: "1"
const response = await axios.put('/api/cart/addcart', {
count: cart.count,
productId: "5ffd153b41bada58d8b12d92",
})
console.log(response)
}catch(error){
// catchErrors(error, setError)
} catch (error) {
catchErrors(error, setError)
}
alert("상품등록이 완료되었습니다.")
}
useEffect(() => {
if (Object.keys(select).length == 2) {
setCart({ ...select })
setSelect({})
}
}, [select])
useEffect(() => {
handleCreate()
getProduct()
}, [cart])
// useEffect(() => {
// handleCreate()
// }, [product])
return (
<div>
{/* {getProduct} */}
{console.log(cart)}
<style type="text/css">
{`
.btn {
......@@ -115,22 +110,22 @@ function Product() {
<Form style={{ borderBottom: "1px solid" }}>
<Form.Group style={{ borderBottom: "1px solid", paddingBottom: "2rem" }}>
<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>
<option>블랙(스트랩포함)</option>
{product.colors.map((e) => (
<option>{e}</option>
))}
</Form.Control>
<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>M</option>
<option>L</option>
<option>XL</option>
<option>FREE</option>
{product.sizes.map((e) => (
<option>{e}</option>
))}
</Form.Control>
</Form.Group>
<div id="list"></div>
{/* {cart.map((e)=>(<div>{e}</div>
))} */}
<Row className="justify-content-between mx-0 my-3" style={{ width: "100%" }}>
<Col> 금액</Col>
<Col className="text-right">14,000</Col>
......
......@@ -2,10 +2,29 @@ import React, { useState, useEffect, useRef } from 'react';
import { Redirect } from 'react-router-dom';
import { Card, Button, Container, Row, Col } from 'react-bootstrap';
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() {
const [num, setNum] = useState(0)
const [error, setError] = useState('')
const [cart, setCart] = useState(INIT_PRODUCT)
const user = isAuthenticated()
useEffect(() => {
getCart()
}, [user])
function plusNum() {
setNum(num + 1)
......@@ -19,46 +38,41 @@ function ShoppingCart() {
}
}
function deleteCart() {
async function deleteCart(e) {
//장바구니 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('카트에 담긴 항목을 삭제했습니다.')
}
// async function getCart(){
// const response = await axios.get('/')
// }
async function getCart() {
// 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 (
<div>
{/* {getCart} */}
{/* {getCart()} */}
{/* {console.log(user)} */}
{/* {console.log(cart)} */}
<Container className="justify-content-center">
<h3 className="my-5 font-weight-bold text-center">장바구니</h3>
<div>
<h4 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h4>
<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="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>
<CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} num={num} />
</div>
<div className="p-5 m-5" style={{ background: '#F7F3F3' }}>
<ul className="pl-0" style={{ listStyle: 'none' }}>
......
......@@ -20,13 +20,14 @@ app.use(cors())
app.use(express.static(path.join(process.cwd(), 'dist')))
// app.use(bodyParser.urlencoded({ extended: true }))
app.use('/images', express.static('uploads/'))
// app.use('/', indexRouter);
app.use('/', kakaopayRoutes)
app.use('/api/users',userRouter)
app.use('/api/auth',authRouter)
app.use('/api/product', productRouter)
app.use('/api/addcart', cartRouter)
app.use('/api/cart', cartRouter)
app.listen(config.port, () => {
console.info('Server started on port %s.', config.port)
......
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(로컬)
const addcart = async (req, res) => {
console.log(req.body)
const { count, productId } = req.body
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)
const newProduct = { count, product: productId }
await Cart.findOneAndUpdate(
{ _id: cart._id },
{ $addToSet: { products: newProduct } }
)
res.json(newCart)
}
// const newCart = await new Cart({
// user, pro_name, price, stock, main_category, sub_category, main_image
// }).save()
// const asdf = await Cart.find({ user })
// console.log(newCart)
// res.json(newCart)
} catch (error) {
console.log(error)
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
// User.findById(id)
// if (!user) {
// console.log(error)
// res.status(404).send('사용자를 찾을 수 없습니다')
// }
// req.profile = user
// next()
// } catch (error) {
// console.log(error)
// res.status(500).send('사용자 아이디 실패')
// }
} catch (error) {
console.log(error)
res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
}
}
export default { cart }
\ No newline at end of file
const deletecart = async (req, res) => {
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
......@@ -6,25 +6,26 @@ const signup = async (req, res) => {
console.log(req.body)
const { name, number1, number2, id, password, tel } = req.body
try {
if(!isLength(password,{min:8, max:15})){
if (!isLength(password, { min: 8, max: 15 })) {
return res.status(422).send('비밀번호는 8-15자리로 입력해주세요.')
}
const user=await User.findOne({id})
if(user){
const user = await User.findOne({ id })
if (user) {
return res.status(422).send(`${id}가 이미 사용중입니다.`)
}
const hash=await bcrypt.hash(password,10)
const hash = await bcrypt.hash(password, 10)
const newUser = await new User ({
const newUser = await new User({
name,
number1,
number2,
id,
password:hash,
password: hash,
tel,
}).save()
await new Cart({ user: newUser._id }).save()
console.log(newUser)
res.json(newUser)
......
......@@ -4,8 +4,16 @@ import cartCtrl from '../controllers/cart.controller.js';
const router = express.Router()
router.route('/')
.post(cartCtrl.cart)
// .get()
router.route('/addcart')
.put(cartCtrl.addcart)
// .get()
router.route('/showcart/:userId')
.get(cartCtrl.showcart)
router.param('userId', cartCtrl.userById)
router.route('/deletecart')
.post(cartCtrl.deletecart)
export default router
\ No newline at end of file
import mongoose from 'mongoose'
const { String, Number, Array, ObjectId } = mongoose.Schema.Types
const productschema = new mongoose.Schema ({
pro_name: {
type: String,
required: true
const CartSchema = new mongoose.Schema({
userId: {
type: ObjectId,
ref: 'User'
},
price:{
products: {
type: [
{
count: {
type: Number,
required: true
},
main_image: {
type: String,
required: true
default: 1
},
color:{
type: String,
required: true
},
size:{
type: String,
required: true
},
productObjectId: {
product: {
type: ObjectId,
required: true
ref: 'Product'
}
})
const CartSchema = new mongoose.Schema({
userId: {
type: String,
// required: true
},
products : {
type: [productschema],
required: true
}
}, {
timestamps: true
]
}
})
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