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

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

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