Commit be29f536 authored by kusang96's avatar kusang96
Browse files

자잘한 사항 수정중

parent e6b07325
import React from 'react' import React from 'react'
import { Card, Col, Row } from 'react-bootstrap' import { Card, Col, Row } from 'react-bootstrap'
function OrderCard(props) { function OrderCard(props) {
return ( return (
...@@ -41,7 +39,6 @@ function OrderCard(props) { ...@@ -41,7 +39,6 @@ function OrderCard(props) {
) )
} }
</Card> </Card>
) )
} }
......
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Card, Image, Container, Row, Col, Button, Form, Modal } from 'react-bootstrap';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import OrderCard from '../Components/OrderCard';
import axios from 'axios'; import axios from 'axios';
import catchError from '../utils/catchErrors'; import catchError from '../utils/catchErrors';
import { isAuthenticated } from '../utils/auth'; import { isAuthenticated } from '../utils/auth';
import OrderCard from '../Components/OrderCard'; import { Card, Image, Container, Row, Col, Button, Form, Modal } from 'react-bootstrap';
const INIT_ACCOUNT = { const INIT_ACCOUNT = {
name: "", name: "",
...@@ -21,6 +21,7 @@ function Account() { ...@@ -21,6 +21,7 @@ function Account() {
async function getUsername(user) { async function getUsername(user) {
try { try {
setError('')
const response = await axios.get(`/api/users/account/${user}`) const response = await axios.get(`/api/users/account/${user}`)
setAccount(response.data) setAccount(response.data)
} catch (error) { } catch (error) {
...@@ -63,6 +64,7 @@ function Account() { ...@@ -63,6 +64,7 @@ function Account() {
const formData = new FormData() const formData = new FormData()
formData.append('avatar', account.avatar[0]) formData.append('avatar', account.avatar[0])
try { try {
setError('')
if (userId) { if (userId) {
const response = await axios.put(`/api/users/account/${userId}`, formData) const response = await axios.put(`/api/users/account/${userId}`, formData)
window.location.reload() window.location.reload()
...@@ -77,18 +79,15 @@ function Account() { ...@@ -77,18 +79,15 @@ function Account() {
async function getOrdered() { async function getOrdered() {
try { try {
const response = await axios.post(`/api/users/addorder`, { setError('')
userId: userId const response = await axios.post(`/api/users/addorder`, { userId: userId })
}) const res = response.data
const a = response.data setOrdered(res)
setOrdered(a)
console.log("what=", response.data)
} catch (error) { } catch (error) {
catchError(error, setError) catchError(error, setError)
} }
} }
return ( return (
<Container className="px-3"> <Container className="px-3">
<style type="text/css"> <style type="text/css">
...@@ -122,8 +121,7 @@ function Account() { ...@@ -122,8 +121,7 @@ function Account() {
</Modal.Body> </Modal.Body>
<Modal.Footer> <Modal.Footer>
<Col className="px-0"> <Col className="px-0">
<Button variant="outline-secondary" onClick={handleBasic} <Button variant="outline-secondary" onClick={handleBasic} className="d-flex justify-content-start"><small>기본이미지로</small></Button>
className="d-flex justify-content-start"><small>기본이미지로</small></Button>
</Col> </Col>
<Button variant="secondary" onClick={() => setShow(false)}>취소</Button> <Button variant="secondary" onClick={() => setShow(false)}>취소</Button>
<Button variant="primary" type="submit" onClick={() => setShow(false)}>저장</Button> <Button variant="primary" type="submit" onClick={() => setShow(false)}>저장</Button>
...@@ -182,7 +180,7 @@ function Account() { ...@@ -182,7 +180,7 @@ function Account() {
</Card> </Card>
<div className='m-2 mb-5'> <div className='m-2 mb-5'>
<OrderCard ordered={ordered} /> <OrderCard ordered={ordered} />
</div> </div>
</Container > </Container >
) )
} }
......
...@@ -20,6 +20,7 @@ function Home() { ...@@ -20,6 +20,7 @@ function Home() {
async function getProductlist() { async function getProductlist() {
try { try {
setError('')
const response = await axios.get(`/api/product/getproduct`) const response = await axios.get(`/api/product/getproduct`)
setProductlist({ bestProduct: response.data.bestProduct, newProduct: response.data.newProduct }) setProductlist({ bestProduct: response.data.bestProduct, newProduct: response.data.newProduct })
} catch (error) { } catch (error) {
......
...@@ -124,7 +124,7 @@ function Payment({ match, location }) { ...@@ -124,7 +124,7 @@ function Payment({ match, location }) {
setCompleteState(false) setCompleteState(false)
setPaymentWay([]) setPaymentWay([])
} else { } else {
const a = ( const bankList = (
<Row className="justify-content-md-center"> <Row className="justify-content-md-center">
<Col md={6} className="border m-5 p-5"> <Col md={6} className="border m-5 p-5">
<Form> <Form>
...@@ -146,14 +146,12 @@ function Payment({ match, location }) { ...@@ -146,14 +146,12 @@ function Payment({ match, location }) {
</Form.Group> </Form.Group>
</Form> </Form>
</Col> </Col>
</Row>) </Row>)
setPaymentWay(a) setPaymentWay(bankList)
} }
} }
async function kakaopay() { async function kakaopay() {
setCompleteState("kakaopay") setCompleteState("kakaopay")
setPaymentWay( setPaymentWay(
<div className="text-center"> <div className="text-center">
...@@ -192,6 +190,7 @@ function Payment({ match, location }) { ...@@ -192,6 +190,7 @@ function Payment({ match, location }) {
} else { } else {
itemNames = cart[0].productId.pro_name itemNames = cart[0].productId.pro_name
} }
setError('')
const response = await fetch('/api/kakaopay/test/single', { const response = await fetch('/api/kakaopay/test/single', {
method: "POST", method: "POST",
headers: { headers: {
......
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react';
import axios from 'axios'; import axios from 'axios';
import { isAuthenticated } from '../utils/auth' import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
import { Card, Row, Col, Button, Alert } from 'react-bootstrap'; import { Card, Row, Col, Button } from 'react-bootstrap';
import { Link } from 'react-router-dom';
function PaymentCompleted() { function PaymentCompleted() {
const user = isAuthenticated() const user = isAuthenticated()
const [error, setError] = useState() const [error, setError] = useState()
const [order, setOrder] = useState([]) const [order, setOrder] = useState([])
...@@ -22,7 +20,6 @@ function PaymentCompleted() { ...@@ -22,7 +20,6 @@ function PaymentCompleted() {
try { try {
setError('') setError('')
const response = await axios.get(`/api/order/showorder/${user}`) const response = await axios.get(`/api/order/showorder/${user}`)
console.log(response.data)
setNum(response.data._id) setNum(response.data._id)
setOrder(response.data.products) setOrder(response.data.products)
setTotal(response.data.total) setTotal(response.data.total)
...@@ -31,6 +28,7 @@ function PaymentCompleted() { ...@@ -31,6 +28,7 @@ function PaymentCompleted() {
catchErrors(error, setError) catchErrors(error, setError)
} }
} }
return ( return (
<div> <div>
<div className="mx-3 my-5 text-center px-3 py-4 border"> <div className="mx-3 my-5 text-center px-3 py-4 border">
...@@ -46,7 +44,6 @@ function PaymentCompleted() { ...@@ -46,7 +44,6 @@ function PaymentCompleted() {
<h3 className="text-center font-weight-bold my-3">주문내역</h3> <h3 className="text-center font-weight-bold my-3">주문내역</h3>
<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>
<div className="m-3"> <div className="m-3">
<Row> <Row>
<Col xs={4} className="text-right">이름</Col> <Col xs={4} className="text-right">이름</Col>
<Col>{receiverInfo.name}</Col> <Col>{receiverInfo.name}</Col>
...@@ -61,7 +58,6 @@ function PaymentCompleted() { ...@@ -61,7 +58,6 @@ function PaymentCompleted() {
</Row> </Row>
</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>
{order.map((e) => ( {order.map((e) => (
<Card className="mx-2"> <Card className="mx-2">
<Row className="mx-1"> <Row className="mx-1">
...@@ -92,4 +88,4 @@ function PaymentCompleted() { ...@@ -92,4 +88,4 @@ function PaymentCompleted() {
) )
} }
export default PaymentCompleted export default PaymentCompleted
\ No newline at end of file
...@@ -22,7 +22,6 @@ function Product({ match, location }) { ...@@ -22,7 +22,6 @@ function Product({ match, location }) {
useEffect(() => { useEffect(() => {
if (size && color) { if (size && color) {
pushOptions() pushOptions()
// console.log(cart)
} }
}, [size, color]) }, [size, color])
...@@ -32,14 +31,13 @@ function Product({ match, location }) { ...@@ -32,14 +31,13 @@ function Product({ match, location }) {
} }
function pushOptions() { function pushOptions() {
// console.log(cart) const cartSet = cart.map(el => {
const a = cart.map(el => { const newObj = {}
const rObj = {} newObj["color"] = el.color;
rObj["color"] = el.color; newObj["size"] = el.size;
rObj["size"] = el.size; return newObj
return rObj
}) })
const isDuplicated = a.some(el => el.color === color && el.size === size) const isDuplicated = cartSet.some(el => el.color === color && el.size === size)
if (isDuplicated) { if (isDuplicated) {
selected.sizes = false selected.sizes = false
selected.colors = false selected.colors = false
...@@ -54,7 +52,6 @@ function Product({ match, location }) { ...@@ -54,7 +52,6 @@ function Product({ match, location }) {
setSize("") setSize("")
setPrice(product.price + price) setPrice(product.price + price)
} }
} }
function handleChange(e) { function handleChange(e) {
...@@ -71,11 +68,11 @@ function Product({ match, location }) { ...@@ -71,11 +68,11 @@ function Product({ match, location }) {
function deleteOption(e) { function deleteOption(e) {
e.preventDefault() e.preventDefault()
let preprice = 0 let preprice = 0
const asd = cart.filter((el) => el.color !== e.target.id || el.size !== e.target.name) const list = cart.filter((el) => el.color !== e.target.id || el.size !== e.target.name)
asd.map((el) => { list.map((el) => {
preprice = preprice + el.count * product.price preprice = preprice + el.count * product.price
}) })
setCart(asd) setCart(list)
setPrice(Number(preprice)) setPrice(Number(preprice))
} }
......
...@@ -4,7 +4,6 @@ import { Row, Col, Button, Form, Container, Alert, Spinner } from 'react-bootstr ...@@ -4,7 +4,6 @@ import { Row, Col, Button, Form, Container, Alert, Spinner } from 'react-bootstr
import axios from 'axios'; import axios from 'axios';
import catchErrors from '../utils/catchErrors'; import catchErrors from '../utils/catchErrors';
function ProductsRegist() { function ProductsRegist() {
const INIT_PRODUCT = { const INIT_PRODUCT = {
pro_name: '', pro_name: '',
...@@ -29,13 +28,13 @@ function ProductsRegist() { ...@@ -29,13 +28,13 @@ function ProductsRegist() {
const [error, setError] = useState('') const [error, setError] = useState('')
const [success, setSuccess] = useState(false) const [success, setSuccess] = useState(false)
const [checked, setChecked] = useState({ "Free": false, "XL": false, "L": false, "M": false, "S": false, "XS": false }) const [checked, setChecked] = useState({ "Free": false, "XL": false, "L": false, "M": false, "S": false, "XS": false })
const [disabled, setDisabled] = useState(true)
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const selectRef = useRef(null) const selectRef = useRef(null)
const colorRef = useRef(null) const colorRef = useRef(null)
useEffect(async () => { useEffect(async () => {
try { try {
setError('')
const response = await axios.get('/api/categories/main') const response = await axios.get('/api/categories/main')
const data = response.data[0] const data = response.data[0]
setCategories([Object.keys(data), Object.values(data)]) setCategories([Object.keys(data), Object.values(data)])
...@@ -44,11 +43,6 @@ function ProductsRegist() { ...@@ -44,11 +43,6 @@ function ProductsRegist() {
} }
}, []) }, [])
useEffect(() => {
const isProduct = Object.values(product).every(el => { console.log("el=", el); Boolean(el) })
isProduct ? setDisabled(false) : setDisabled(true)
}, [product])
function deleteCategory(e) { function deleteCategory(e) {
const pdcate = product.sub_category.filter((el) => el !== e.target.name) const pdcate = product.sub_category.filter((el) => el !== e.target.name)
setProduct({ ...product, "sub_category": pdcate }) setProduct({ ...product, "sub_category": pdcate })
...@@ -78,8 +72,6 @@ function ProductsRegist() { ...@@ -78,8 +72,6 @@ function ProductsRegist() {
} }
function deleteColor(e) { function deleteColor(e) {
console.log(product.colors)
console.log(e.target.name)
const pdcolors = product.colors.filter((el) => el !== e.target.name) const pdcolors = product.colors.filter((el) => el !== e.target.name)
setProduct({ ...product, "colors": pdcolors }) setProduct({ ...product, "colors": pdcolors })
} }
...@@ -106,7 +98,6 @@ function ProductsRegist() { ...@@ -106,7 +98,6 @@ function ProductsRegist() {
} }
} }
product["sizes"] = sizes product["sizes"] = sizes
console.log(product)
const formData = new FormData(); const formData = new FormData();
for (let key in product) { for (let key in product) {
if (key === "main_image") { if (key === "main_image") {
...@@ -124,7 +115,6 @@ function ProductsRegist() { ...@@ -124,7 +115,6 @@ function ProductsRegist() {
setLoading(true) setLoading(true)
setError('') setError('')
const response = await axios.post('/api/product/regist', formData) const response = await axios.post('/api/product/regist', formData)
console.log(response)
setSuccess(true) setSuccess(true)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
...@@ -140,7 +130,6 @@ function ProductsRegist() { ...@@ -140,7 +130,6 @@ function ProductsRegist() {
return ( return (
<Container> <Container>
{console.log(product)}
<Row className="justify-content-md-center"> <Row className="justify-content-md-center">
<Col md={8} className="border p-1" style={{ background: '#F7F3F3' }}> <Col md={8} className="border p-1" style={{ background: '#F7F3F3' }}>
{error && <Alert variant="danger" className="text-center">{error}</Alert>} {error && <Alert variant="danger" className="text-center">{error}</Alert>}
......
...@@ -79,9 +79,7 @@ function ProductsList({ match }) { ...@@ -79,9 +79,7 @@ function ProductsList({ match }) {
} }
async function handleSort(method) { async function handleSort(method) {
console.log(method)
if (method === "purchase") { if (method === "purchase") {
console.log("thisispurchase")
productlist.sort(function (a, b) { productlist.sort(function (a, b) {
if (a.purchase > b.purchase) { if (a.purchase > b.purchase) {
return -1; return -1;
...@@ -89,12 +87,10 @@ function ProductsList({ match }) { ...@@ -89,12 +87,10 @@ function ProductsList({ match }) {
if (a.purchase < b.purchase) { if (a.purchase < b.purchase) {
return 1; return 1;
} }
// a must be equal to b
return 0; return 0;
}); });
setSortingName("인기상품") setSortingName("인기상품")
} else if (method === "newest") { } else if (method === "newest") {
console.log("thisisnewest")
productlist.sort(function (a, b) { productlist.sort(function (a, b) {
if (a.createdAt > b.createdAt) { if (a.createdAt > b.createdAt) {
return -1; return -1;
...@@ -102,13 +98,10 @@ function ProductsList({ match }) { ...@@ -102,13 +98,10 @@ function ProductsList({ match }) {
if (a.createdAt < b.createdAt) { if (a.createdAt < b.createdAt) {
return 1; return 1;
} }
// a must be equal to b
return 0; return 0;
}); });
setSortingName("신상품") setSortingName("신상품")
} else if (method === "lowest") { } else if (method === "lowest") {
console.log("thisislowest")
productlist.sort(function (a, b) { productlist.sort(function (a, b) {
if (a.price > b.price) { if (a.price > b.price) {
return 1; return 1;
...@@ -116,12 +109,10 @@ function ProductsList({ match }) { ...@@ -116,12 +109,10 @@ function ProductsList({ match }) {
if (a.price < b.price) { if (a.price < b.price) {
return -1; return -1;
} }
// a must be equal to b
return 0; return 0;
}); });
setSortingName("낮은가격") setSortingName("낮은가격")
} else { } else {
console.log("thisispurchase")
productlist.sort(function (a, b) { productlist.sort(function (a, b) {
if (a.price > b.price) { if (a.price > b.price) {
return -1; return -1;
...@@ -129,14 +120,12 @@ function ProductsList({ match }) { ...@@ -129,14 +120,12 @@ function ProductsList({ match }) {
if (a.price < b.price) { if (a.price < b.price) {
return 1; return 1;
} }
// a must be equal to b
return 0; return 0;
}); });
setSortingName("높은가격") setSortingName("높은가격")
} }
} }
async function handleSubname(e) { async function handleSubname(e) {
const subname = e.target.name const subname = e.target.name
try { try {
...@@ -168,7 +157,7 @@ function ProductsList({ match }) { ...@@ -168,7 +157,7 @@ function ProductsList({ match }) {
border-color: #CDC5C2; border-color: #CDC5C2;
border-radius: 0; border-radius: 0;
} }
.btn:hover { .btn:hover, .btn-primary:focus {
background-color: #91877F; background-color: #91877F;
border-color: #91877F; border-color: #91877F;
box-shadow: 0 0 0 0; box-shadow: 0 0 0 0;
...@@ -177,9 +166,6 @@ function ProductsList({ match }) { ...@@ -177,9 +166,6 @@ function ProductsList({ match }) {
background-color: #91877F; background-color: #91877F;
border-color: #91877F; border-color: #91877F;
} }
.show>.btn-primary.dropdown-toggle:focus {
box-shadow: 0 0 0 0;
}
.dropdown-item { .dropdown-item {
color: #91877F; color: #91877F;
} }
......
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { Button, Container, Row, Col } from 'react-bootstrap'; import CartCard from '../Components/CartCard';
import axios from 'axios'; 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 { Button, Container } from 'react-bootstrap';
function ShoppingCart() { function ShoppingCart() {
const [error, setError] = useState('') const [error, setError] = useState('')
...@@ -15,13 +15,12 @@ function ShoppingCart() { ...@@ -15,13 +15,12 @@ function ShoppingCart() {
useEffect(() => { useEffect(() => {
getCart() getCart()
// console.log(cart)
}, [user]) }, [user])
function plusNum(e) { function plusNum(e) {
const addCount = cart.map((el) => { const addCount = cart.map((el) => {
if (el._id === e.target.name) { if (el._id === e.target.name) {
return { ...el, count: el.count+1} return { ...el, count: el.count + 1 }
} else { } else {
return { ...el } return { ...el }
} }
...@@ -31,7 +30,7 @@ function ShoppingCart() { ...@@ -31,7 +30,7 @@ function ShoppingCart() {
function minusNum(e) { function minusNum(e) {
const addCount = cart.map((el) => { const addCount = cart.map((el) => {
if (el._id === e.target.name) { if (el._id === e.target.name) {
return { ...el, count: el.count-1 } return { ...el, count: el.count - 1 }
} else { } else {
return { ...el } return { ...el }
} }
...@@ -48,29 +47,26 @@ function ShoppingCart() { ...@@ -48,29 +47,26 @@ function ShoppingCart() {
return { ...el } return { ...el }
} }
}) })
const asd = cartCheck.filter((el) => el.checked === true) const list = cartCheck.filter((el) => el.checked === true)
asd.map((el)=>{ list.map((el) => {
price = el.count*el.productId.price + price price = el.count * el.productId.price + price
}) })
setFinalPrice(price) setFinalPrice(price)
setCart(cartCheck) setCart(cartCheck)
setFinalCart(asd) setFinalCart(list)
} }
async function deleteCart(e) { async function deleteCart(e) {
//장바구니 DB에서 해당 항목 삭제
// console.log(e.target.name)
try { try {
setError('')
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)
setCart(response.data.products) setCart(response.data.products)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
// console.log('카트에 담긴 항목을 삭제했습니다.')
} }
async function getCart() { async function getCart() {
...@@ -78,23 +74,21 @@ function ShoppingCart() { ...@@ -78,23 +74,21 @@ function ShoppingCart() {
setError('') setError('')
const response = await axios.get(`/api/cart/showcart/${user}`) const response = await axios.get(`/api/cart/showcart/${user}`)
const addChecked = response.data.map((el) => { const addChecked = response.data.map((el) => {
return { ...el, checked: false } return { ...el, checked: false }
}) })
console.log("addchecked=",addChecked)
setCart(addChecked) setCart(addChecked)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
} }
function putCheckedCart(){ function putCheckedCart() {
try { try {
setError('') setError('')
const response = axios.post(`/api/cart/changecart`, { const response = axios.post(`/api/cart/changecart`, {
userId:user, userId: user,
products: cart products: cart
}) })
console.log(response.data)
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
...@@ -102,7 +96,6 @@ function ShoppingCart() { ...@@ -102,7 +96,6 @@ function ShoppingCart() {
return ( return (
<div> <div>
{/* {console.log(cart)} */}
<Container className="justify-content-center"> <Container className="justify-content-center">
<h1 className="my-5 font-weight-bold text-center">장바구니</h1> <h1 className="my-5 font-weight-bold text-center">장바구니</h1>
<div> <div>
...@@ -110,7 +103,6 @@ function ShoppingCart() { ...@@ -110,7 +103,6 @@ function ShoppingCart() {
{cart.length > 0 {cart.length > 0
? <CartCard cart={cart} deleteCart={deleteCart} minusNum={minusNum} plusNum={plusNum} checkedCart={checkedCart} /> ? <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>
<div className="p-5 m-3" 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' }}>
...@@ -130,7 +122,7 @@ function ShoppingCart() { ...@@ -130,7 +122,7 @@ function ShoppingCart() {
<div className="text-center"> <div className="text-center">
<Button as={Link} to={{ <Button as={Link} to={{
pathname: `/payment`, pathname: `/payment`,
state: finalCart state: finalCart
}} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} onClick={putCheckedCart} block>결제하기</Button> }} className="px-5" style={{ background: "#91877F", borderColor: '#91877F' }} onClick={putCheckedCart} block>결제하기</Button>
</div> </div>
</Container> </Container>
......
import React, { useState } from 'react'; 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'; import { Redirect } from 'react-router-dom';
import axios from 'axios';
import catchErrors from '../utils/catchErrors';
import { Form, Col, Container, Button, Row, Alert } from 'react-bootstrap';
const INIT_USER = { const INIT_USER = {
name: '', name: '',
...@@ -33,7 +33,6 @@ function Signup() { ...@@ -33,7 +33,6 @@ function Signup() {
event.stopPropagation(); event.stopPropagation();
} }
setValidated(true); setValidated(true);
try { try {
setError('') setError('')
const response = await axios.post('/api/users/signup', user) const response = await axios.post('/api/users/signup', user)
...@@ -46,13 +45,11 @@ function Signup() { ...@@ -46,13 +45,11 @@ function Signup() {
function checkPassword(event) { function checkPassword(event) {
const p1 = user.password const p1 = user.password
const p2 = user.password2 const p2 = user.password2
if (p1 !== p2) { if (p1 !== p2) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
alert('비밀번호가 일치하지 않습니다.') alert('비밀번호가 일치하지 않습니다.')
return false return false
} else { } else {
return true return true
} }
...@@ -68,14 +65,11 @@ function Signup() { ...@@ -68,14 +65,11 @@ function Signup() {
<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 pt-3 m-4">Sign Up</h2> <h2 className="text-center pt-3 m-4">Sign Up</h2>
{error && <Alert variant='danger'> {error && <Alert variant='danger'>{error}</Alert>}
{error}
</Alert>}
<Form <Form
noValidate validated={validated} noValidate validated={validated}
onSubmit={handleSubmit} onSubmit={handleSubmit}
className="p-4"> className="p-4">
<Form.Group as={Row} controlId="formBasicName"> <Form.Group as={Row} controlId="formBasicName">
<Form.Label column sm="4" for='name'> <Form.Label column sm="4" for='name'>
</Form.Label> </Form.Label>
...@@ -89,7 +83,6 @@ function Signup() { ...@@ -89,7 +83,6 @@ function Signup() {
<Form.Control.Feedback type="invalid" >이름을 입력하세요. </Form.Control.Feedback> <Form.Control.Feedback type="invalid" >이름을 입력하세요. </Form.Control.Feedback>
</Col> </Col>
</Form.Group> </Form.Group>
<Form.Group as={Row} controlId="formBasicNumber"> <Form.Group as={Row} controlId="formBasicNumber">
<Form.Label column sm="4" for='number'> <Form.Label column sm="4" for='number'>
주민등록번호 </Form.Label> 주민등록번호 </Form.Label>
......
...@@ -24,10 +24,8 @@ const app = express(); ...@@ -24,10 +24,8 @@ const app = express();
app.use(express.json()) app.use(express.json())
app.use(cors()) 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('/images', express.static('uploads/')) app.use('/images', express.static('uploads/'))
// app.use('/', indexRouter);
app.use('/', kakaopayRoutes) app.use('/', kakaopayRoutes)
app.use('/api/categories',categoryRouter) app.use('/api/categories',categoryRouter)
app.use('/api/users',userRouter) app.use('/api/users',userRouter)
......
...@@ -50,4 +50,4 @@ const getsubId = async (req, res, next, ele) => { ...@@ -50,4 +50,4 @@ const getsubId = async (req, res, next, ele) => {
next() next()
} }
export default { getCategory, getsubId, getSubCategory, getToHome } export default { getCategory, getsubId, getSubCategory, getToHome }
\ No newline at end of file
// import { RequestHandler } from "express";
import fetch from 'node-fetch' import fetch from 'node-fetch'
import config from "../config.js"; import config from "../config.js";
...@@ -30,7 +29,6 @@ const singleTest = async (req, res) => { ...@@ -30,7 +29,6 @@ const singleTest = async (req, res) => {
console.log("asdaf") console.log("asdaf")
console.log(req.body) console.log(req.body)
const item = req.body const item = req.body
// set data
const data = [] const data = []
for (let property in item) { for (let property in item) {
let encodedKey = encodeURIComponent(property); let encodedKey = encodeURIComponent(property);
...@@ -38,7 +36,6 @@ const singleTest = async (req, res) => { ...@@ -38,7 +36,6 @@ const singleTest = async (req, res) => {
data.push(encodedKey + "=" + encodedValue); data.push(encodedKey + "=" + encodedValue);
} }
const bodyData = data.join('&') // encode data (application/x-www-form-urlencoded) const bodyData = data.join('&') // encode data (application/x-www-form-urlencoded)
const response = await fetch('https://kapi.kakao.com/v1/payment/ready', { const response = await fetch('https://kapi.kakao.com/v1/payment/ready', {
method: 'POST', method: 'POST',
headers: { headers: {
...@@ -47,16 +44,9 @@ const singleTest = async (req, res) => { ...@@ -47,16 +44,9 @@ const singleTest = async (req, res) => {
}, },
body: bodyData, body: bodyData,
}) })
// console.log(response)
const resp = await response.json() const resp = await response.json()
console.log(resp) console.log(resp)
res.json({redirect_url: resp.next_redirect_pc_url}) res.json({redirect_url: resp.next_redirect_pc_url})
} }
export default { export default { success, fail, cancel, singleTest }
success, \ No newline at end of file
fail,
cancel,
singleTest,
}
...@@ -4,9 +4,7 @@ import User from "../schemas/User.js"; ...@@ -4,9 +4,7 @@ import User from "../schemas/User.js";
const addorder = async (req, res) => { const addorder = async (req, res) => {
const { userId, products, receiverInfo, total } = req.body const { userId, products, receiverInfo, total } = req.body
try { try {
const newOrder = await new Order({ const newOrder = await new Order({ userId, products, receiverInfo, total }).save()
userId, products, receiverInfo, total
}).save()
res.status(200).send('Order DB에 저장 완료') res.status(200).send('Order DB에 저장 완료')
} catch (error) { } catch (error) {
console.log(error) console.log(error)
...@@ -17,8 +15,7 @@ const addorder = async (req, res) => { ...@@ -17,8 +15,7 @@ const addorder = async (req, res) => {
const Ordered = async (req, res) => { const Ordered = async (req, res) => {
const { db } = req.body const { db } = req.body
try { try {
const ordered = await req.body.findOne({}, { _id: 0}).select(`${db}`) const ordered = await req.body.findOne({}, { _id: 0 }).select(`${db}`)
console.log("sub= ",ordered);
res.json(ordered); res.json(ordered);
} catch (error) { } catch (error) {
res.status(500).send('카테고리를 불러오지 못했습니다.') res.status(500).send('카테고리를 불러오지 못했습니다.')
...@@ -27,11 +24,10 @@ const Ordered = async (req, res) => { ...@@ -27,11 +24,10 @@ const Ordered = async (req, res) => {
const showorder = async (req, res) => { const showorder = async (req, res) => {
try { try {
const order = await Order.find({ userId: req.userId }).sort({_id:-1}).limit(1).populate({ const order = await Order.find({ userId: req.userId }).sort({ _id: -1 }).limit(1).populate({
path: 'products.productId', path: 'products.productId',
model: 'Product' model: 'Product'
}) })
console.log(order)
res.status(200).json(order[0]) res.status(200).json(order[0])
} catch (error) { } catch (error) {
console.log(error) console.log(error)
...@@ -39,6 +35,27 @@ const showorder = async (req, res) => { ...@@ -39,6 +35,27 @@ const showorder = async (req, res) => {
} }
} }
const recommendPro = async (req, res) => {
const { productId } = req.body
console.log(productId)
try {
const findedorder = await Order.find({ 'products.productId': productId })
console.log('findedouder=', findedorder)
const recommend = await
const recommend = await Order.aggregate([
// { $project: {}},
{$match: {"products":{"productId": productId}}},
{$group: {
_id: "$products.productId",
num_tutorial: { $sum: 1 }
}
}
])
console.log('recommend=', recommend)
} catch (error) {
}
}
const orderById = async (req, res, next, id) => { const orderById = async (req, res, next, id) => {
try { try {
...@@ -54,4 +71,4 @@ const orderById = async (req, res, next, id) => { ...@@ -54,4 +71,4 @@ const orderById = async (req, res, next, id) => {
} }
} }
export default { addorder, showorder, orderById , Ordered } export default { addorder, showorder, orderById, Ordered }
\ No newline at end of file \ No newline at end of file
...@@ -5,7 +5,7 @@ const upload = multer({ dest: 'uploads/' }) ...@@ -5,7 +5,7 @@ const upload = multer({ dest: 'uploads/' })
const imageUpload = upload.fields([ const imageUpload = upload.fields([
{ name: 'main_image' }, { name: 'main_image' },
{ name: 'detail_image'} { name: 'detail_image' }
]) ])
const regist = async (req, res) => { const regist = async (req, res) => {
......
...@@ -13,7 +13,6 @@ const imgUpload = uploadimg.fields([ ...@@ -13,7 +13,6 @@ const imgUpload = uploadimg.fields([
const username = (req, res) => { const username = (req, res) => {
res.json(req.account) res.json(req.account)
console.log(req.account)
} }
const userById = async (req, res, next, id) => { const userById = async (req, res, next, id) => {
...@@ -30,10 +29,8 @@ const userById = async (req, res, next, id) => { ...@@ -30,10 +29,8 @@ const userById = async (req, res, next, id) => {
} }
} }
const signup = async (req, res) => { const signup = async (req, res) => {
const { name, number1, number2, id, password, tel, email } = req.body const { name, number1, number2, id, password, tel, email } = req.body
console.log("whatup", 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자리로 입력해주세요.')
...@@ -42,9 +39,7 @@ const signup = async (req, res) => { ...@@ -42,9 +39,7 @@ const signup = async (req, res) => {
if (user) { if (user) {
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({
name, name,
number1, number1,
...@@ -57,7 +52,6 @@ const signup = async (req, res) => { ...@@ -57,7 +52,6 @@ const signup = async (req, res) => {
await new Cart({ userId: newUser._id }).save() await new Cart({ userId: newUser._id }).save()
console.log(newUser) console.log(newUser)
res.json(newUser) res.json(newUser)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
res.status(500).send('죄송합니다. 다시 입력해 주십시오.') res.status(500).send('죄송합니다. 다시 입력해 주십시오.')
...@@ -65,7 +59,6 @@ const signup = async (req, res) => { ...@@ -65,7 +59,6 @@ const signup = async (req, res) => {
} }
const update = async (req, res) => { const update = async (req, res) => {
console.log("req", req.body)
try { try {
if (req.body.avatar == '') { if (req.body.avatar == '') {
const user = req.account const user = req.account
...@@ -79,7 +72,6 @@ const update = async (req, res) => { ...@@ -79,7 +72,6 @@ const update = async (req, res) => {
const updateUser = await user.save() const updateUser = await user.save()
res.json(updateUser) res.json(updateUser)
} }
} catch (error) { } catch (error) {
console.log(error); console.log(error);
res.status(500).send('이미지 업데이트 실패') res.status(500).send('이미지 업데이트 실패')
...@@ -87,13 +79,12 @@ const update = async (req, res) => { ...@@ -87,13 +79,12 @@ const update = async (req, res) => {
} }
const addorder = async (req, res) => { const addorder = async (req, res) => {
const {userId}=req.body const { userId } = req.body
try { try {
const order = await Order.find({ userId: userId }).populate({ const order = await Order.find({ userId: userId }).populate({
path: 'products.productId', path: 'products.productId',
model: 'Product' model: 'Product'
}) })
console.log("hey", order)
res.status(200).json(order) res.status(200).json(order)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
...@@ -101,5 +92,4 @@ const addorder = async (req, res) => { ...@@ -101,5 +92,4 @@ const addorder = async (req, res) => {
} }
} }
export default { signup, username, imgUpload, userById, update, addorder }
export default { signup, username, imgUpload, userById,update, addorder } \ No newline at end of file
\ No newline at end of file
import express from "express"; import express from "express";
import cartCtrl from '../controllers/cart.controller.js'; import cartCtrl from '../controllers/cart.controller.js';
const router = express.Router() const router = express.Router()
router.route('/addcart') router.route('/addcart')
.put(cartCtrl.addCart) .put(cartCtrl.addCart)
// .get()
router.route('/showcart/:userId') router.route('/showcart/:userId')
.get(cartCtrl.showCart) .get(cartCtrl.showCart)
......
import express from "express"; import express from "express";
import orderCtrl from '../controllers/order.controller.js'; import orderCtrl from '../controllers/order.controller.js';
const router = express.Router() const router = express.Router()
router.route('/addorder') router.route('/addorder')
.post(orderCtrl.addorder) .post(orderCtrl.addorder)
// .get()
router.route('/showorder/:userId') router.route('/showorder/:userId')
.get(orderCtrl.showorder) .get(orderCtrl.showorder)
......
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