Commit 7953e3c1 authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

cartDB 오류가 있지만 어쨌든 돌아가긴함

parent 9af5d81a
...@@ -2,8 +2,6 @@ import React from 'react' ...@@ -2,8 +2,6 @@ import React from 'react'
import { Card, Button, Container, Row, Col } from 'react-bootstrap'; import { Card, Button, Container, Row, Col } from 'react-bootstrap';
function CartCard(props) { function CartCard(props) {
return ( return (
<> <>
{props.cart.map((e) => ( {props.cart.map((e) => (
...@@ -13,13 +11,13 @@ function CartCard(props) { ...@@ -13,13 +11,13 @@ function CartCard(props) {
<input className="" type="checkbox" id="exampleCheck1" /> <input className="" type="checkbox" id="exampleCheck1" />
</Col> </Col>
<Col className="text-center"> <Col className="text-center">
<Card.Img className="img-fluid" variant="top" src={e.main_image && `/images/${e.main_image}`} style={{ width: '20rem' }} /> <Card.Img className="img-fluid" variant="top" src={e.productId.main_image && `/images/${e.productId.main_image}`} style={{ width: '20rem' }} />
</Col> </Col>
<Col md={6} className="p-2"> <Col md={6} className="p-2">
<Card.Body> <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} /> <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.Title className="font-weight-bold mt-3">{e.productId.pro_name}</Card.Title>
<Card.Text>가격: {e.price}</Card.Text> <Card.Text>가격: {e.productId.price}</Card.Text>
<Card.Text>옵션: {e.sizes}/{e.colors}</Card.Text> <Card.Text>옵션: {e.sizes}/{e.colors}</Card.Text>
<Card.Text>수량</Card.Text> <Card.Text>수량</Card.Text>
<div> <div>
......
...@@ -6,18 +6,29 @@ import catchErrors from '../utils/catchErrors'; ...@@ -6,18 +6,29 @@ import catchErrors from '../utils/catchErrors';
const INIT_PRODUCT = { const INIT_PRODUCT = {
pro_name: '스키니진', pro_name: '스키니진',
price: 12000, price: 12000,
count:1, count: 1,
main_category: 'PANTS', main_category: 'PANTS',
sub_category: ['SKINNY JEANS'], sub_category: ['SKINNY JEANS'],
sizes: [ 'L', 'M'], sizes: ['L', 'M'],
colors: ['연청', '진청'], colors: ['연청', '진청'],
main_image: "a8f4d63ead77717f940a2b27deb707a6" main_image: "a8f4d63ead77717f940a2b27deb707a6",
productId:"5ffda03428faf35de8319360"
} }
const preCart = []
function Product() { function Product() {
const [product, setProduct] = useState(INIT_PRODUCT) const [product, setProduct] = useState(INIT_PRODUCT)
const [cart, setCart] = useState(INIT_PRODUCT) const [cart, setCart] = useState(INIT_PRODUCT)
const [error, setError] = useState('') const [error, setError] = useState('')
const [selected, setSelected] = useState({ sizes: false, colors: false })
const [n, setN] = useState(1)
useEffect(() => {
if (selected.sizes === true && selected.colors === true) {
pushOptions()
console.log(preCart)
}
}, [cart])
function handleClick(e) { function handleClick(e) {
...@@ -25,10 +36,24 @@ function Product() { ...@@ -25,10 +36,24 @@ function Product() {
box.style.display = "none" box.style.display = "none"
} }
function pushOptions() {
preCart.push(cart)
selected.sizes = false
selected.colors = false
setN(n+1)
}
function handleChange(e) { function handleChange(e) {
const { name, value } = e.target const { name, value } = e.target
if (e.target.name === "sizes") {
setCart({ ...cart, [name]: value })
selected.sizes = true
} else if (e.target.name === "colors") {
setCart({ ...cart, [name]: value })
selected.colors = true
}
// setCart({ ...cart, [name]: value })
// handleCreate() // handleCreate()
setCart({ ...cart, [name]: value })
} }
function listDelete(e) { function listDelete(e) {
...@@ -39,29 +64,29 @@ function Product() { ...@@ -39,29 +64,29 @@ function Product() {
function handleCreate() { function handleCreate() {
console.log("실행", "cart=", product) console.log("실행", "cart=", product)
if (product !== undefined) { // if (product !== undefined) {
if (product.colors !== "" && product.sizes !== "") { // if (product.colors !== "" && product.sizes !== "") {
cart.push( // cart.push(
<div className="d-flex justify-content-between my-2" > // <div className="d-flex justify-content-between my-2" >
<p>{product.color} {product.size} </p> // <p>{product.color} {product.size} </p>
<input name="count" type="number" min="0" max="10" style="width: 40px" onChange={handleChange} /> // <input name="count" type="number" min="0" max="10" style="width: 40px" onChange={handleChange} />
<p style="margin-bottom: 0px">{product.price}</p> // <p style="margin-bottom: 0px">{product.price}</p>
</div> // </div>
) // )
// const list = document.getElementById('list') // const list = document.getElementById('list')
// list.style.borderBottom = "1px solid" // list.style.borderBottom = "1px solid"
// const shopping = document.createElement('div') // const shopping = document.createElement('div')
// shopping.className = "d-flex justify-content-between my-2" // shopping.className = "d-flex justify-content-between my-2"
// shopping.innerHTML = `${product.color} / ${product.size} // shopping.innerHTML = `${product.color} / ${product.size}
// <input type="number" min="0" max="10" value="1" style="width: 40px" /> // <input type="number" min="0" max="10" value="1" style="width: 40px" />
// <p style="margin-bottom: 0px">14,000원</p>` // <p style="margin-bottom: 0px">14,000원</p>`
// const deleteA = document.createElement('a') // const deleteA = document.createElement('a')
// deleteA.innerText = 'X' // deleteA.innerText = 'X'
// deleteA.addEventListener('click', listDelete) // deleteA.addEventListener('click', listDelete)
// shopping.appendChild(deleteA) // shopping.appendChild(deleteA)
// list.appendChild(shopping) // list.appendChild(shopping)
} // }
} // }
} }
async function addCart() { async function addCart() {
...@@ -69,8 +94,9 @@ function Product() { ...@@ -69,8 +94,9 @@ function Product() {
try { try {
// setError('') // setError('')
const response = await axios.put('/api/cart/addcart', { const response = await axios.put('/api/cart/addcart', {
count: cart.count, userId: localStorage.getItem('loginStatus'),
productId: "5ffd153b41bada58d8b12d92", productId: "a8f4d63ead77717f940a2b27deb707a6",
products: preCart
}) })
console.log(response) console.log(response)
} catch (error) { } catch (error) {
...@@ -124,8 +150,9 @@ function Product() { ...@@ -124,8 +150,9 @@ function Product() {
))} ))}
</Form.Control> </Form.Control>
</Form.Group> </Form.Group>
{/* {cart.map((e)=>(<div>{e}</div> {preCart.map((e) => (
))} */} <div>{e.colors}/{e.sizes}</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>
......
...@@ -5,21 +5,12 @@ import axios from 'axios'; ...@@ -5,21 +5,12 @@ import axios from 'axios';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
import { isAuthenticated } from '../utils/auth' import { isAuthenticated } from '../utils/auth'
import CartCard from '../Components/CartCard'; 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 [error, setError] = useState('')
const [cart, setCart] = useState(INIT_PRODUCT) const [cart, setCart] = useState()
const user = isAuthenticated() const user = isAuthenticated()
useEffect(() => { useEffect(() => {
...@@ -71,7 +62,7 @@ function ShoppingCart() { ...@@ -71,7 +62,7 @@ function ShoppingCart() {
<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>
<CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} num={num} /> {cart?<CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} num={num} />:<div></div>}
</div> </div>
<div className="p-5 m-5" style={{ background: '#F7F3F3' }}> <div className="p-5 m-5" style={{ background: '#F7F3F3' }}>
......
...@@ -2,6 +2,7 @@ import React, { useState } from 'react'; ...@@ -2,6 +2,7 @@ import React, { useState } from 'react';
import axios from 'axios' import axios from 'axios'
import { Form, Col, Container, Button, Row, Alert } from 'react-bootstrap' import { Form, Col, Container, Button, Row, Alert } from 'react-bootstrap'
import catchErrors from '../utils/catchErrors' import catchErrors from '../utils/catchErrors'
import { Redirect } from 'react-router-dom';
const INIT_USER = { const INIT_USER = {
name: '', name: '',
...@@ -13,21 +14,19 @@ const INIT_USER = { ...@@ -13,21 +14,19 @@ const INIT_USER = {
} }
function Signup() { function Signup() {
const [user, setUser] = useState(true) const [user, setUser] = useState(INIT_USER)
const [error, setError] = useState('') const [error, setError] = useState('')
const [success, setSuccess] = useState(false)
const [validated, setValidated] = useState(false); const [validated, setValidated] = useState(false);
function handleChange(event) { function handleChange(event) {
const { name, value } = event.target const { name, value } = event.target
setUser({ ...user, [name]: value }) setUser({ ...user, [name]: value })
} }
async function handleSubmit(event) { async function handleSubmit(event) {
event.preventDefault() event.preventDefault()
const form = event.currentTarget; const form = event.currentTarget;
console.log(form)
if (form.checkValidity() === false) { if (form.checkValidity() === false) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
...@@ -39,154 +38,159 @@ const [validated, setValidated] = useState(false); ...@@ -39,154 +38,159 @@ const [validated, setValidated] = useState(false);
setError('') setError('')
const response = await axios.post('/api/users/signup', user) const response = await axios.post('/api/users/signup', user)
console.log(response.data) console.log(response.data)
setSuccess(true)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
} }
function checkPassword(event){
const p1=user.password
const p2=user.password2
if(p1 !== p2){
function checkPassword(event) {
const p1 = user.password
const p2 = user.password2
if (p1 !== p2) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
alert('비밀번호가 일치하지 않습니다.') alert('비밀번호가 일치하지 않습니다.')
return false return false
}else{ } else {
return true return true
} }
} }
return ( if (success) {
<div> alert('회원가입 되었습니다.')
<Container className="my-5"> return <Redirect to='/login'/>
}
return (
<div>
<Container className="my-5">
<Row className="justify-content-center"> <Row className="justify-content-center">
<Col md={6} xs={10} className="border" style={{ background: '#F7F3F3' }}> <Col md={6} xs={10} className="border" style={{ background: '#F7F3F3' }}>
<h2 className="text-center mt-5">Sign Up</h2> <h2 className="text-center mt-5">Sign Up</h2>
{error && <Alert variant='danger'> {error && <Alert variant='danger'>
{error} {error}
</Alert>} </Alert>}
<Form <Form
noValidate validated={validated} noValidate validated={validated}
onSubmit={handleSubmit} onSubmit={handleSubmit}
className="p-5"> className="p-5">
<Form.Group controlId="formBasicName"> <Form.Group controlId="formBasicName">
<Form.Row> <Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="id"> </Col> <Col sm={4} xs={6} as={Form.Label} for="id"> </Col>
<Col sm={8} xs={12} as={Form.Control} <Col sm={8} xs={12} as={Form.Control}
required type="text"
name="name"
placeholder="Name"
style={{ width: '160px' }}
value={user.name}
onChange={handleChange} />
<Form.Control.Feedback type="invalid">이름을 입력하세요. </Form.Control.Feedback>
</Form.Row>
</Form.Group>
<Form.Group controlId="formBasicNumber">
<Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="number">주민등록번호</Col>
<Col as={Row} sm={8} xs={10} >
<Form.Control
required type="text" required type="text"
name="name" name="number1"
placeholder="Name" maxlength="6"
style={{ width: '160px' }} className="mx-2" style={{ width: '17 0px' }}
value={user.name} value={user.number1}
onChange={handleChange} /> onChange={handleChange}>
<Form.Control.Feedback type="invalid">이름을 입력하세요. </Form.Control.Feedback> </Form.Control>
</Form.Row>
</Form.Group>
<Form.Group controlId="formBasicNumber">
<Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="number">주민등록번호</Col>
<Col as={Row} sm={8} xs={10} >
<Form.Control
required type="text"
name="number1"
maxlength="6"
className="mx-2" style={{ width: '17 0px' }}
value={user.number1}
onChange={handleChange}>
</Form.Control>
- -
<Form.Control <Form.Control
required type="text" required type="text"
name="number2" name="number2"
maxlength="1" className="mx-3" maxlength="1" className="mx-3"
style={{ width: '50px' }} style={{ width: '50px' }}
value={user.number2} value={user.number2}
onChange={handleChange}> onChange={handleChange}>
</Form.Control> </Form.Control>
****** ******
<Form.Control.Feedback type="invalid">주민등록번호를 입력하세요.</Form.Control.Feedback> <Form.Control.Feedback type="invalid">주민등록번호를 입력하세요.</Form.Control.Feedback>
</Col> </Col>
</Form.Row> </Form.Row>
</Form.Group> </Form.Group>
<Form.Group controlId="formBasicId"> <Form.Group controlId="formBasicId">
<Form.Row> <Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="id">아이디</Col> <Col sm={4} xs={6} as={Form.Label} for="id">아이디</Col>
<Col sm={8} xs={12} as={Form.Control} <Col sm={8} xs={12} as={Form.Control}
required required
type="text" type="text"
name="id" name="id"
placeholder="ID" placeholder="ID"
style={{ width: '160px' }} style={{ width: '160px' }}
value={user.id} value={user.id}
onChange={handleChange} /> onChange={handleChange} />
<Form.Control.Feedback type="invalid"> 아이디를 입력하세요.</Form.Control.Feedback> <Form.Control.Feedback type="invalid"> 아이디를 입력하세요.</Form.Control.Feedback>
</Form.Row> </Form.Row>
</Form.Group> </Form.Group>
<Form.Group controlId="formBasicPassword"> <Form.Group controlId="formBasicPassword">
<Form.Row> <Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="password">비밀번호</Col> <Col sm={4} xs={6} as={Form.Label} for="password">비밀번호</Col>
<Col sm={8} xs={12} as={Form.Control} <Col sm={8} xs={12} as={Form.Control}
type="password" type="password"
name="password" name="password"
placeholder="Password" placeholder="Password"
style={{ width: '160px' }} style={{ width: '160px' }}
value={user.password} value={user.password}
required required
onChange={handleChange} onChange={handleChange}
/> />
<Form.Control.Feedback className="text-center" type="invalid"> <Form.Control.Feedback className="text-center" type="invalid">
비밀번호를 입력하세요. 비밀번호를 입력하세요.
</Form.Control.Feedback> </Form.Control.Feedback>
</Form.Row> </Form.Row>
</Form.Group> </Form.Group>
<Form.Group controlId="formBasicPassword2"> <Form.Group controlId="formBasicPassword2">
<Form.Row> <Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="password">비밀번호 확인</Col> <Col sm={4} xs={6} as={Form.Label} for="password">비밀번호 확인</Col>
<Col sm={8} xs={12} as={Form.Control} <Col sm={8} xs={12} as={Form.Control}
type="password" type="password"
name="password2" name="password2"
placeholder="Password" placeholder="Password"
style={{ width: '160px' }} style={{ width: '160px' }}
value={user.password2} value={user.password2}
required required
onChange={handleChange} onChange={handleChange}
/> />
<Form.Control.Feedback type="invalid"> 비밀번호를 한번 입력하세요. <Form.Control.Feedback type="invalid"> 비밀번호를 한번 입력하세요.
</Form.Control.Feedback> </Form.Control.Feedback>
</Form.Row> </Form.Row>
</Form.Group> </Form.Group>
<Form.Group controlId="formBasicTel"> <Form.Group controlId="formBasicTel">
<Form.Row> <Form.Row>
<Col sm={4} xs={6} as={Form.Label} for="tel">휴대전화</Col> <Col sm={4} xs={6} as={Form.Label} for="tel">휴대전화</Col>
<Col sm={8} xs={12} as={Form.Control} <Col sm={8} xs={12} as={Form.Control}
required required
type="text" type="text"
name="tel" name="tel"
size="sm" style={{ width: '160px' }} size="sm" style={{ width: '160px' }}
value={user.tel} value={user.tel}
onChange={handleChange} /> onChange={handleChange} />
<Form.Control.Feedback type="invalid"> 휴대전화를 입력하세요. </Form.Control.Feedback> <Form.Control.Feedback type="invalid"> 휴대전화를 입력하세요. </Form.Control.Feedback>
</Form.Row> </Form.Row>
</Form.Group> </Form.Group>
<Button <Button
style={{ background: '#91877F', borderColor: '#91877F' }} type="submit" block style={{ background: '#91877F', borderColor: '#91877F' }} type="submit" block
onClick={checkPassword} onClick={checkPassword}
> >
Sign Up Sign Up
</Button> </Button>
</Form> </Form>
</Col> </Col>
</Row> </Row>
</Container> </Container>
</div> </div>
) )
} }
export default Signup export default Signup
\ No newline at end of file
import Cart from "../schemas/Cart.js"; import Cart from "../schemas/Cart.js";
const addcart = async (req, res) => { const addcart = async (req, res) => {
console.log(req.body) // console.log(req.body)
const { count, productId } = req.body const { userId, products} = req.body
try { try {
const newProduct = { count, product: productId } const cart = await Cart.findOne({ userId: userId })
await Cart.findOneAndUpdate( console.log(cart)
// const newProduct = { products: products }
// const newProduct = {...newProduct}
// console.log(newProduct)
console.log(products)
await Cart.updateOne(
{ _id: cart._id }, { _id: cart._id },
{ $addToSet: { products: newProduct } } // { $addToSet: { products: newProduct } }
{$set: {products: products}}
) )
res.json(newCart) res.status(200).send('Cart updated')
} catch (error) { } catch (error) {
console.log(error) console.log(error)
res.status(500).send('죄송합니다. 다시 입력해 주십시오.') res.status(500).send('죄송합니다. 다시 입력해 주십시오.')
...@@ -18,15 +25,15 @@ const addcart = async (req, res) => { ...@@ -18,15 +25,15 @@ const addcart = async (req, res) => {
const showcart = async (req, res) => { const showcart = async (req, res) => {
// const {userId} = req.body // const {userId} = req.body
console.log(req.cart) // console.log(req.cart)
// console.log(req.id)
try { try {
const cart = await Cart.findOne({ user: userId }).populate({ const cart = await Cart.findOne({ userId: req.id }).populate({
path: 'products.product', path: 'products.productId',
model: 'Product' model: 'Product'
}) })
res.status(200).json(cart.products) res.status(200).json(cart.products)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
res.status(500).send('쇼핑카트를 불러오지 못했습니다.') res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
...@@ -53,6 +60,7 @@ const userById = async (req, res, next, id) => { ...@@ -53,6 +60,7 @@ const userById = async (req, res, next, id) => {
res.status(404).send("사용자를 찾을 수 없습니다.") res.status(404).send("사용자를 찾을 수 없습니다.")
} }
req.cart = cart req.cart = cart
req.id = id
next() next()
} catch (error) { } catch (error) {
res.status(500).send("사용자 아이디 검색 실패") res.status(500).send("사용자 아이디 검색 실패")
......
import Cart from "../schemas/Cart.js";
import User from "../schemas/User.js"; import User from "../schemas/User.js";
import isLength from 'validator/lib/isLength.js' import isLength from 'validator/lib/isLength.js';
import bcrypt from 'bcryptjs' import bcrypt from 'bcryptjs';
const signup = async (req, res) => { const signup = async (req, res) => {
console.log(req.body)
const { name, number1, number2, id, password, tel } = req.body const { name, number1, number2, id, password, tel } = req.body
console.log(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자리로 입력해주세요.')
...@@ -14,7 +17,6 @@ const signup = async (req, res) => { ...@@ -14,7 +17,6 @@ const signup = async (req, res) => {
return res.status(422).send(`${id}가 이미 사용중입니다.`) 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({
...@@ -25,7 +27,7 @@ const signup = async (req, res) => { ...@@ -25,7 +27,7 @@ const signup = async (req, res) => {
password: hash, password: hash,
tel, tel,
}).save() }).save()
await new Cart({ user: newUser._id }).save() await new Cart({ userId: newUser._id }).save()
console.log(newUser) console.log(newUser)
res.json(newUser) res.json(newUser)
...@@ -35,5 +37,4 @@ const signup = async (req, res) => { ...@@ -35,5 +37,4 @@ const signup = async (req, res) => {
} }
} }
export default { signup }
export default { signup } \ No newline at end of file
...@@ -13,9 +13,15 @@ const CartSchema = new mongoose.Schema({ ...@@ -13,9 +13,15 @@ const CartSchema = new mongoose.Schema({
type: Number, type: Number,
default: 1 default: 1
}, },
product: { productId: {
type: ObjectId, type: ObjectId,
ref: 'Product' ref: 'Product'
},
sizes: {
type: String
},
colors: {
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