Commit 4ae42d2f authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

orderDB저장

parent 8258442f
import React from 'react' import React from 'react'
import { Card, Button, Container, Row, Col } from 'react-bootstrap'; import { Card, Row, Col } from 'react-bootstrap';
function CartCard(props) { function CartCard(props) {
console.log(props)
return ( return (
<> <>
{props.cart.map((e) => ( {props.cart.map((e) => (
<Card> <Card>
<Row className="mx-1"> <Row className="mx-1">
<Col xs={2} sm={2} className="text-center my-auto"> <Col xs={2} sm={2} className="text-center my-auto">
<input className="" type="checkbox" id="exampleCheck1" /> <input className="" type="checkbox" name={String(e._id)} onChange={props.checkedCart} />
</Col> </Col>
<Col className="text-center"> <Col className="text-center">
<Card.Img className="img-fluid" variant="top" src={e.productId.main_imgUrl && `/images/${e.productId.main_imgUrl}`} style={{ width: '20rem' }} /> <Card.Img className="img-fluid" variant="top" src={e.productId.main_imgUrl && `/images/${e.productId.main_imgUrl}`} style={{ width: '20rem' }} />
...@@ -17,13 +18,13 @@ function CartCard(props) { ...@@ -17,13 +18,13 @@ function CartCard(props) {
<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.productId.pro_name}</Card.Title> <Card.Title className="font-weight-bold mt-3">{e.productId.pro_name}</Card.Title>
<Card.Text>가격: {e.productId.price}</Card.Text> <Card.Text>가격: {e.productId.price}</Card.Text>
<Card.Text>옵션: {e.size}/{e.color}</Card.Text> <Card.Text>옵션: {e.size}/{e.color}</Card.Text>
<Card.Text>수량</Card.Text> <Card.Text>수량</Card.Text>
<div> <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="image" name={String(e._id)} 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="number" 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} /> <input type="image" name={String(e._id)} alt="플러스" src="https://img.icons8.com/ios-glyphs/20/000000/plus-math.png" className="align-middle" onClick={props.plusNum} />
</div> </div>
</Card.Body> </Card.Body>
</Col> </Col>
......
import React from 'react' import React from 'react'
import { Card, Row, Col } from 'react-bootstrap';
function PaymentCard() {
function PaymentCard(props) {
return ( return (
<Card > <>
{props.cart.map((e) => (
<Card>
<Row className="mx-1"> <Row className="mx-1">
<Col className="text-center"> <Col className="text-center">
<Card.Img className="img-fluid" variant="top" src="img/asd.jpg" style={{ width: '20rem' }} /> <Card.Img className="img-fluid" variant="top" src={e.productId.main_imgUrl && `/images/${e.productId.main_imgUrl}`} style={{ width: '20rem' }} />
</Col> </Col>
<Col md={6} className="p-2"> <Col md={6} className="p-2">
<Card.Body> <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">{e.productId.pro_name}</Card.Title>
<Card.Title className="font-weight-bold mt-3">제품명</Card.Title> <Card.Text>가격: {e.productId.price}</Card.Text>
<Card.Text>가격</Card.Text> <Card.Text>옵션: {e.size}/{e.color}</Card.Text>
<Card.Text>옵션</Card.Text> <Card.Text>수량: {e.count}</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> </Card.Body>
</Col> </Col>
</Row> </Row>
</Card> </Card>
))
}
</>
) )
} }
......
import axios from 'axios';
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import DaumPostcode from "react-daum-postcode"; import DaumPostcode from "react-daum-postcode";
import { Container, Card, Row, Col, Button, Form, FormGroup } from 'react-bootstrap'; import { Container, Card, Row, Col, Button, Form, FormGroup } from 'react-bootstrap';
import { Redirect } from 'react-router-dom'; import { Redirect } from 'react-router-dom';
import PaymentCard from '../Components/PaymentCard';
import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors';
function Payment() { function Payment({ match, location }) {
const [cart, setCart] = useState(location.state)
const [order, setOrder] = useState({products: location.state})
const [userData, setUserData] = useState({})
const [error, setError] = useState()
const [paymentWay, setPaymentWay] = useState([]) const [paymentWay, setPaymentWay] = useState([])
const [isAddress, setIsAddress] = useState(""); // const [isAddress, setIsAddress] = useState("");
const [isZoneCode, setIsZoneCode] = useState(); // const [isZoneCode, setIsZoneCode] = useState();
const [isPostOpen, setIsPostOpen] = useState(); // const [isPostOpen, setIsPostOpen] = useState();
const [post, setPost] = useState([]) const [post, setPost] = useState([])
const [redirect, setRedirect] = useState(null) const [redirect, setRedirect] = useState(null)
const [address, setAddress] = useState("") const [address, setAddress] = useState("")
const [finalPrice, setFinalPrice] = useState(0)
const [num, setNum] = useState(0) const [num, setNum] = useState(0)
const user = isAuthenticated()
useEffect(() => {
getUser()
let price = 0
cart.map((el) => {
price = Number(el.count) * Number(el.productId.price) + price
})
setFinalPrice(price)
}, [user])
async function getUser() {
try {
const response = await axios.get(`/api/users/getuser/${user}`)
console.log(response.data)
setUserData(response.data)
} catch (error) {
catchErrors(error, setError)
}
}
function handleReceiverInfo(e) {
const { name, value } = e.target
console.log(name,value)
setOrder({ ...order, receiverInfo: {...order.receiverInfo, [name]: value } })
}
function postClick() { function postClick() {
if (post.length !== 0) { if (post.length !== 0) {
...@@ -42,8 +77,8 @@ function Payment() { ...@@ -42,8 +77,8 @@ function Payment() {
} }
fullAddress += extraAddress !== "" ? ` (${extraAddress})` : ""; fullAddress += extraAddress !== "" ? ` (${extraAddress})` : "";
} }
setAddress({ full: fullAddress, zone: data.zonecode }); setAddress({ full: fullAddress, code: data.zonecode });
setOrder({ ...order, receiverInfo: {...order.receiverInfo, address: fullAddress, postalCode: data.zonecode } })
console.log(fullAddress); console.log(fullAddress);
} }
...@@ -89,12 +124,6 @@ function Payment() { ...@@ -89,12 +124,6 @@ function Payment() {
} }
} }
function handleClick2() {
if (paymentWay.length !== 0) {
setPaymentWay([])
}
}
async function kakaopay() { async function kakaopay() {
const response = await fetch('/api/kakaopay/test/single', { const response = await fetch('/api/kakaopay/test/single', {
method: "POST", method: "POST",
...@@ -121,21 +150,20 @@ function Payment() { ...@@ -121,21 +150,20 @@ function Payment() {
// setRedirect(data.redirect_url) // setRedirect(data.redirect_url)
} }
function plusNum() { async function paymentCompleted(){
setNum(num + 1) console.log(user)
} console.log(order)
function minusNum() { console.log(finalPrice)
if (num === 0) { try {
setNum(0) const response = await axios.post(`/api/order/addorder`, {
} userId : user,
else { ...order,
setNum(num - 1) total : finalPrice+2500
})
} console.log(response.data)
} catch (error) {
catchErrors(error, setError)
} }
function deleteCart() {
//장바구니 DB에서 해당 항목 삭제
console.log('카트에 담긴 항목을 삭제했습니다.')
} }
if (redirect) { if (redirect) {
...@@ -145,6 +173,7 @@ function Payment() { ...@@ -145,6 +173,7 @@ function Payment() {
return ( return (
<div> <div>
{/* {console.log(order)} */}
<Container> <Container>
<h3 className="my-5 font-weight-bold text-center">주문/결제</h3> <h3 className="my-5 font-weight-bold text-center">주문/결제</h3>
<div> <div>
...@@ -154,15 +183,15 @@ function Payment() { ...@@ -154,15 +183,15 @@ function Payment() {
<Form> <Form>
<Form.Group controlId="formBasicName"> <Form.Group controlId="formBasicName">
<Form.Label>이름</Form.Label> <Form.Label>이름</Form.Label>
<Form.Control type="text" placeholder="윤지원" /> <Form.Control type="text" value={userData.name} readOnly />
</Form.Group>
<Form.Group controlId="formBasicEmail">
<Form.Label>이메일</Form.Label>
<Form.Control type="email" placeholder="jiwon5393@naver.com" />
</Form.Group> </Form.Group>
<Form.Group controlId="formBasicTel"> <Form.Group controlId="formBasicTel">
<Form.Label>휴대전화</Form.Label> <Form.Label>휴대전화</Form.Label>
<Form.Control type="tel" placeholder="010-0000-0000" /> <Form.Control type="tel" value={userData.tel} readOnly />
</Form.Group>
<Form.Group controlId="formBasicEmail">
<Form.Label>이메일</Form.Label>
<Form.Control type="email" placeholder="이메일 주소를 입력해주세요" />
</Form.Group> </Form.Group>
</Form> </Form>
</Col> </Col>
...@@ -176,13 +205,17 @@ function Payment() { ...@@ -176,13 +205,17 @@ function Payment() {
<Form> <Form>
<Form.Group> <Form.Group>
<Form.Label>이름</Form.Label> <Form.Label>이름</Form.Label>
<Form.Control></Form.Control> <Form.Control type="text" name="name" onChange={handleReceiverInfo}></Form.Control>
</Form.Group>
<Form.Group>
<Form.Label>휴대전화</Form.Label>
<Form.Control type="text" name="tel" onChange={handleReceiverInfo}></Form.Control>
</Form.Group> </Form.Group>
<Form.Group controlId="formBasicAdd"> <Form.Group controlId="formBasicAdd">
<Form.Label>주소</Form.Label> <Form.Label>주소</Form.Label>
<Form.Row> <Form.Row>
<Col xs={4} sm={4}> <Col xs={4} sm={4}>
<Form.Control type="text" id="add" value={address.zone} disabled={(address.zone == null) ? false : true} placeholder="우편번호" required ></Form.Control> <Form.Control type="text" name="postalCode" id="add" onChange={handleReceiverInfo} value={address.code} disabled={(address.code == null) ? false : true} placeholder="우편번호" required ></Form.Control>
</Col> </Col>
<Col > <Col >
<Button style={{ background: '#91877F', borderColor: '#91877F' }} className="mx-1" onClick={postClick}>우편번호</Button> <Button style={{ background: '#91877F', borderColor: '#91877F' }} className="mx-1" onClick={postClick}>우편번호</Button>
...@@ -191,16 +224,12 @@ function Payment() { ...@@ -191,16 +224,12 @@ function Payment() {
</Form.Row> </Form.Row>
<Form.Row> <Form.Row>
<Col> <Col>
<Form.Control type="text" id="add1" value={address.full} disabled={(address.zone == null) ? false : true} placeholder="주소" required></Form.Control> <Form.Control type="text" name="address" id="add1" onChange={handleReceiverInfo} value={address.full} disabled={(address.code == null) ? false : true} placeholder="주소" required></Form.Control>
<Form.Control type="text" id="add2" placeholder="상세주소" required></Form.Control> <Form.Control type="text" name="address2" id="add2" onChange={handleReceiverInfo} placeholder="상세주소" required></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>
<Form.Label>휴대전화</Form.Label>
<Form.Control></Form.Control>
</Form.Group>
</Form> </Form>
</Col> </Col>
</Row> </Row>
...@@ -208,42 +237,22 @@ function Payment() { ...@@ -208,42 +237,22 @@ function Payment() {
<div> <div>
<h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5> <h5 className="font-weight-bold py-3 border-top border-bottom text-center" style={{ background: '#F7F3F3' }}>주문상품정보</h5>
<Card > <PaymentCard cart={cart} />
<Row className="mx-1">
<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-3" style={{ background: '#F7F3F3' }}>
<ul className="pl-0" style={{ listStyle: 'none' }}> <ul className="pl-0" style={{ listStyle: 'none' }}>
<li> <li>
<span className="text-secondary"> 상품금액</span> <span className="text-secondary"> 상품금액</span>
<span className="text-secondary float-right">12,000</span> <span className="text-secondary float-right">{finalPrice}</span>
</li> </li>
<li> <li>
<span className="text-secondary">배송비</span> <span className="text-secondary">배송비</span>
<span className="text-secondary float-right">2,500</span> <span className="text-secondary float-right">2500</span>
</li> </li>
</ul> </ul>
<div className="my-1 pt-2 border-top font-weight-bold"> <div className="my-1 pt-2 border-top font-weight-bold">
결제금액<span className="float-right">14,500</span> 결제금액<span className="float-right">{finalPrice + 2500}</span>
</div> </div>
</div> </div>
...@@ -256,7 +265,7 @@ function Payment() { ...@@ -256,7 +265,7 @@ function Payment() {
{paymentWay} {paymentWay}
</div> </div>
<div className="text-center"> <div className="text-center">
<Button className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} href="/account" block>결제완료</Button> <Button className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} onClick={paymentCompleted} block>결제완료</Button>
</div> </div>
</Container> </Container>
</div> </div>
......
...@@ -40,11 +40,9 @@ function Product({ match, location }) { ...@@ -40,11 +40,9 @@ function Product({ match, location }) {
function handleChange(e) { function handleChange(e) {
const { name, value } = e.target const { name, value } = e.target
if (name === "sizes") { if (name === "sizes") {
// setPreCart({ ...preCart, [name]: value })
setSize(value) setSize(value)
selected.sizes = true selected.sizes = true
} else if (name === "colors") { } else if (name === "colors") {
// setPreCart({ ...preCart, [name]: value })
setColor(value) setColor(value)
selected.colors = true selected.colors = true
} }
...@@ -58,17 +56,14 @@ function Product({ match, location }) { ...@@ -58,17 +56,14 @@ function Product({ match, location }) {
function handleCount(e) { function handleCount(e) {
e.preventDefault() e.preventDefault()
// const asd = cart.filter((el) => el.color !== e.target.id || el.size !== e.target.name) const addCount = cart.map((el)=>{
const asd= cart.map((el)=>{
if(el.color !== e.target.id || el.size !== e.target.name){ if(el.color !== e.target.id || el.size !== e.target.name){
return {el} return {el}
} else { } else {
return {...el, count : e.target.value} return {...el, count : e.target.value}
} }
}) })
// const index = product["sub_category"].findIndex((item)=>{return item === e.target.name}) setCart(addCount)
// product["sub_category"].splice(index, 1)
setCart(asd)
setCount(e.value) setCount(e.value)
} }
...@@ -80,7 +75,6 @@ function Product({ match, location }) { ...@@ -80,7 +75,6 @@ function Product({ match, location }) {
setError('') setError('')
const response = await axios.put('/api/cart/addcart', { const response = await axios.put('/api/cart/addcart', {
userId: localStorage.getItem('id'), userId: localStorage.getItem('id'),
// productId: product.id,
products: cart products: cart
}) })
console.log(response) console.log(response)
......
...@@ -124,7 +124,6 @@ function ProductsRegist() { ...@@ -124,7 +124,6 @@ function ProductsRegist() {
const formData = new FormData(); const formData = new FormData();
for (let key in product) { for (let key in product) {
if (key === "main_image" ||key === "detail_image") { if (key === "main_image" ||key === "detail_image") {
// console.log(product[key][0])
formData.append(key, product[key][0]) formData.append(key, product[key][0])
} else if(key === "sizes" || key === "colors"){ } else if(key === "sizes" || key === "colors"){
for (let i = 0; i < product[key].length ; i++){ for (let i = 0; i < product[key].length ; i++){
...@@ -135,7 +134,6 @@ function ProductsRegist() { ...@@ -135,7 +134,6 @@ function ProductsRegist() {
formData.append(key, product[key]) formData.append(key, product[key])
} }
} }
// console.log(formData)
try { try {
const response = await axios.post('/api/product/regist', formData) const response = await axios.post('/api/product/regist', formData)
console.log(response) console.log(response)
......
...@@ -7,53 +7,80 @@ import { isAuthenticated } from '../utils/auth' ...@@ -7,53 +7,80 @@ import { isAuthenticated } from '../utils/auth'
import CartCard from '../Components/CartCard'; import CartCard from '../Components/CartCard';
function ShoppingCart() { function ShoppingCart() {
const [num, setNum] = useState()
const [error, setError] = useState('') const [error, setError] = useState('')
const [cart, setCart] = useState([]) const [cart, setCart] = useState([])
const [finalCart, setFinalCart] = useState([])
const [finalPrice, setFinalPrice] = useState(0) const [finalPrice, setFinalPrice] = useState(0)
const user = isAuthenticated() const user = isAuthenticated()
useEffect(() => { useEffect(() => {
getCart() getCart()
console.log(cart)
}, [user]) }, [user])
function plusNum() { function plusNum(e) {
num = num + 1 const addCount = cart.map((el) => {
setNum(num + 1) if (el._id === e.target.name) {
return { ...el, count: el.count+1}
} else {
return { ...el }
} }
function minusNum() { })
if (num === 0) { setCart(addCount)
setNum(0) }
function minusNum(e) {
const addCount = cart.map((el) => {
if (el._id === e.target.name) {
return { ...el, count: el.count-1 }
} else {
return { ...el }
} }
else { })
setNum(num - 1) setCart(addCount)
} }
function checkedCart(e) {
let price = 0
const cartCheck = cart.map((el) => {
if (el._id === e.target.name) {
return { ...el, checked: !el.checked }
} else {
return { ...el }
} }
})
const asd = cartCheck.filter((el) => el.checked === true)
asd.map((el)=>{
price = el.count*el.productId.price + price
})
setFinalPrice(price)
setCart(cartCheck)
setFinalCart(asd)
}
async function deleteCart(e) { async function deleteCart(e) {
//장바구니 DB에서 해당 항목 삭제 //장바구니 DB에서 해당 항목 삭제
console.log(e.target.name) console.log(e.target.name)
try { try {
const response = await axios.post('/api/cart/deletecart', { const response = await axios.post('/api/cart/deletecart', {
userId : user, userId: user,
cartId: e.target.name }) cartId: e.target.name
})
console.log(response.data) console.log(response.data)
setCart(response.data.products) setCart(response.data.products)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
console.log('카트에 담긴 항목을 삭제했습니다.') console.log('카트에 담긴 항목을 삭제했습니다.')
} }
async function getCart() { async function getCart() {
try { try {
const response = await axios.get(`/api/cart/showcart/${user}`) const response = await axios.get(`/api/cart/showcart/${user}`)
console.log(response.data) const addChecked = response.data.map((el) => {
setCart(response.data) return { ...el, checked: false }
const finalPrices = response.data.map((e) => {
return e.count * e.productId.price
}) })
setFinalPrice(finalPrices.reduce((a, b) => (a + b))) console.log("addchecked=",addChecked)
setCart(addChecked)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
...@@ -65,8 +92,8 @@ function ShoppingCart() { ...@@ -65,8 +92,8 @@ function ShoppingCart() {
<h1 className="my-5 font-weight-bold text-center">장바구니</h1> <h1 className="my-5 font-weight-bold text-center">장바구니</h1>
<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>
{cart.length >0 {cart.length > 0
? <CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} num={num} /> ? <CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} checkedCart={checkedCart} />
: <div className="text-center my-5">장바구니에 담긴 상품이 없습니다.</div>} : <div className="text-center my-5">장바구니에 담긴 상품이 없습니다.</div>}
</div> </div>
...@@ -88,7 +115,7 @@ function ShoppingCart() { ...@@ -88,7 +115,7 @@ function ShoppingCart() {
<div className="text-center"> <div className="text-center">
<Button as={Link} to={{ <Button as={Link} to={{
pathname: `/payment`, pathname: `/payment`,
state: { cart } state: finalCart
}} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>결제하기</Button> }} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} block>결제하기</Button>
</div> </div>
</Container> </Container>
......
...@@ -9,6 +9,7 @@ import path from 'path' ...@@ -9,6 +9,7 @@ import path from 'path'
import kakaopayRoutes from './routes/kakaopay.routes.js' import kakaopayRoutes from './routes/kakaopay.routes.js'
import config from './config.js' import config from './config.js'
import authRouter from './routes/auth.routes.js' import authRouter from './routes/auth.routes.js'
import orderRouter from './routes/order.routes.js'
import cors from 'cors' import cors from 'cors'
fs.readdir('uploads', (error) => { fs.readdir('uploads', (error) => {
...@@ -33,6 +34,7 @@ app.use('/api/users',userRouter) ...@@ -33,6 +34,7 @@ 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/cart', cartRouter) app.use('/api/cart', cartRouter)
app.use('/api/order', orderRouter)
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 Order from "../schemas/Order.js";
const addorder = async (req, res) => {
const { userId, products, receiverInfo, total } = req.body
try {
const newOrder = await new Order({
userId, products, receiverInfo, total
}).save()
res.status(200).send('Order DB에 저장 완료')
} catch (error) {
console.log(error)
res.status(500).send('Order DB에 저장 실패')
}
}
const showorder = async (req, res) => {
try {
const order = await Order.findOne({ userId: req.id }).populate({
path: 'products.productId',
model: 'Product'
})
res.status(200).json(order.products)
} catch (error) {
console.log(error)
res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
}
}
export default { addorder, showorder }
\ No newline at end of file
...@@ -6,6 +6,15 @@ import multer from "multer"; ...@@ -6,6 +6,15 @@ import multer from "multer";
const uploadimg = multer({ dest: 'uploads/' }); const uploadimg = multer({ dest: 'uploads/' });
const getUser = async (req, res) => {
try {
const user = await User.findOne({ _id: req.id })
res.json(user)
} catch (error) {
res.status(500).send('사용자 정보를 불러올 수 없습니다.')
}
}
const imgUpload = uploadimg.fields([ const imgUpload = uploadimg.fields([
{ name: 'avatar', maxCount: 1 } { name: 'avatar', maxCount: 1 }
]) ])
...@@ -22,6 +31,7 @@ const userById = async (req, res, next, id) => { ...@@ -22,6 +31,7 @@ const userById = async (req, res, next, id) => {
res.status(404).send('사용자를 찾을 수 없습니다') res.status(404).send('사용자를 찾을 수 없습니다')
} }
req.account = user req.account = user
req.id = id
next() next()
} catch (error) { } catch (error) {
console.log(error); console.log(error);
...@@ -54,7 +64,7 @@ const signup = async (req, res) => { ...@@ -54,7 +64,7 @@ const signup = async (req, res) => {
password: hash, password: hash,
tel, tel,
}).save() }).save()
await new Cart({ userId: newUser._id,role}).save() await new Cart({ userId: newUser._id, role }).save()
console.log(newUser) console.log(newUser)
res.json(newUser) res.json(newUser)
...@@ -86,4 +96,4 @@ const update = async (req, res) => { ...@@ -86,4 +96,4 @@ const update = async (req, res) => {
} }
} }
export default { signup, username, imgUpload, userById, update } export default { getUser, signup, username, imgUpload, userById, update }
\ No newline at end of file \ No newline at end of file
import express from "express";
import orderCtrl from '../controllers/order.controller.js';
const router = express.Router()
router.route('/addorder')
.post(orderCtrl.addorder)
// .get()
router.route('/showorder/:userId')
.get(orderCtrl.showorder)
export default router
\ No newline at end of file
...@@ -10,6 +10,8 @@ router.route('/account/:userId') ...@@ -10,6 +10,8 @@ router.route('/account/:userId')
.get(userCtrl.username) .get(userCtrl.username)
.put(userCtrl.imgUpload, userCtrl.update) .put(userCtrl.imgUpload, userCtrl.update)
router.route('/getuser/:userId')
.get(userCtrl.getUser)
router.param('userId', userCtrl.userById) router.param('userId', userCtrl.userById)
......
import mongoose from 'mongoose'
const { ObjectId, Number, String } = mongoose.Schema.Types
const OrderSchema = new mongoose.Schema({
userId: {
type: ObjectId,
ref: 'User'
},
products: [
{
productId: {
type: ObjectId,
ref: 'Product'
},
count: {
type: Number,
required: true
},
size: {
type: String,
required: true
},
color: {
type: String,
required: true
}
}
],
receiverInfo:
{
name: {
type:String,
required:true
},
tel: {
type: String,
required:true
},
postalCode:{
type:String,
required:true
},
address: {
type: String,
required: true
},
address2: {
type: String,
required: true
}
}
,
total: {
type: Number,
required: true
}
}, {
timestamps: true
})
export default mongoose.models.Order || mongoose.model('Order', OrderSchema)
\ 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