Commit 1169c8dd authored by 박상호's avatar 박상호 🎼
Browse files

mypage is really done :)

parent 62ff8335
...@@ -10,11 +10,11 @@ import ProductRegist from './Pages/ProductRegist'; ...@@ -10,11 +10,11 @@ import ProductRegist from './Pages/ProductRegist';
import ShoppingCart from './Pages/ShoppingCart'; import ShoppingCart from './Pages/ShoppingCart';
import Payment from './Pages/Payment'; import Payment from './Pages/Payment';
import Account from './Pages/Account'; import Account from './Pages/Account';
import EditAccount from './Pages/EditAccount';
import MainNav from './Components/MainNav'; import MainNav from './Components/MainNav';
import SubNav from './Components/SubNav'; import SubNav from './Components/SubNav';
function App() { function App() {
...@@ -34,7 +34,6 @@ function App() { ...@@ -34,7 +34,6 @@ function App() {
<Route path="/shoppingcart" component={ShoppingCart} /> <Route path="/shoppingcart" component={ShoppingCart} />
<Route path="/payment" component={Payment} /> <Route path="/payment" component={Payment} />
<Route path="/account" component={Account} /> <Route path="/account" component={Account} />
<Route path="/editaccount" component={EditAccount} />
<Route path='/kakao' component={() => { window.location.href = 'https://compmath.korea.ac.kr'; return null; }} /> <Route path='/kakao' component={() => { window.location.href = 'https://compmath.korea.ac.kr'; return null; }} />
<Redirect path="/" to="/" /> <Redirect path="/" to="/" />
</Switch> </Switch>
......
...@@ -6,6 +6,7 @@ import option from '../option.svg'; ...@@ -6,6 +6,7 @@ import option from '../option.svg';
import { handleLogout, isAuthenticated } from '../utils/auth' import { handleLogout, isAuthenticated } from '../utils/auth'
function MainNav() { function MainNav() {
const user = isAuthenticated() const user = isAuthenticated()
return ( return (
......
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react'
import { Card, Image, Container, Row, Col, Table, Accordion, Button } from 'react-bootstrap' import { Card, Image, Container, Row, Col, Table, Accordion, Button, Form, Modal, Alert } from 'react-bootstrap'
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import person from '../person.svg'; import person from '../person.svg';
import mypagetiger from '../mypagetiger.svg'; import mypagetiger from '../mypagetiger.svg';
...@@ -9,24 +9,25 @@ import { isAuthenticated } from '../utils/auth'; ...@@ -9,24 +9,25 @@ import { isAuthenticated } from '../utils/auth';
const INIT_ACCOUNT = { const INIT_ACCOUNT = {
name: "", name: "",
tel: "" avatarUrl: ''
} }
function Account() { function Account() {
const [account, setAccount] = useState(INIT_ACCOUNT) const [account, setAccount] = useState(INIT_ACCOUNT)
const [error, setError] = useState("") const [error, setError] = useState("")
const userId = isAuthenticated() const userId = isAuthenticated()
async function getUsername(user) { async function getUsername(user) {
// console.log("tlg")
try { try {
const response = await axios.get(`/api/users/account/${user}`) const response = await axios.get(`/api/users/account/${user}`)
setAccount(response.data) setAccount(response.data)
console.log('555555555', response.data); // console.log('555555555', response.data);
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
console.log('error2222', error) // console.log('error2222', error)
} }
} }
...@@ -34,41 +35,98 @@ function Account() { ...@@ -34,41 +35,98 @@ function Account() {
getUsername(userId) getUsername(userId)
}, [userId]) }, [userId])
const [show, setShow] = useState(false);
// const [account, setAccount] = useState(INIT_ACCOUNT) const handleClose = () => setShow(false)
// const [error, setError] = useState("")
const handleShow = () => setShow(true)
// const user = isAuthenticated()
const handleChange = (event) => {
const { name, value, files } = event.target
if (files) {
for (const file of files) {
// console.log("name=", name, "value=", value, 'file=', file);
}
setAccount({ ...account, [name]: files })
} else {
console.log("name=", name, "value=", value);
setAccount({ ...account, [name]: value })
}
}
// async function getAccount(user) { const handleBasic = async (event) => {
// console.log(user); const formData = new FormData()
// try { formData.append('avatar', '')
// const response = await axios.get("/api/auth/login") try {
// setAccount(response.data) if (userId) {
// console.log(response.data); const response = await axios.put(`/api/users/account/${userId}`, formData)
// } catch (error) { console.log(response.data)
// catchErrors(error, setError) window.location.reload()
// } }
// } } catch (error) {
// useEffect(() => { catchErrors(error, setError)
// getAccount(user) }
// }, [user]) setShow(false)
}
return ( const handleSubmit = async (event) => {
event.preventDefault()
if (account.avatar) {
const formData = new FormData()
formData.append('avatar', account.avatar[0])
try {
if (userId) {
const response = await axios.put(`/api/users/account/${userId}`, formData)
console.log(response.data)
window.location.reload()
}
} catch (error) {
catchErrors(error, setError)
}
} else {
alert("파일을 선택해주세요.")
}
}
return (
<Container className="px-3"> <Container className="px-3">
<h3 className="my-4 mx-3 font-weight-bold">My Page</h3> <h3 className="my-4 mx-3 font-weight-bold">My Page</h3>
<Card md={3} className="p-1 mb-4" style={{ background: '#F7F3F3' }}> <Card md={3} className="p-1 mb-4" style={{ background: '#F7F3F3' }}>
<Row className="p-2"> <Row className="p-2">
<Col md={4} className="d-flex align-content-center justify-content-center"> <Col md={5} className="d-flex align-content-center justify-content-center">
<Button type="button" variant="outline-light">
<Image src={person} roundedCircle className="img-thumbnail" width={"170rem"} /> <Button variant="outline-light" onClick={handleShow}>
{account.avatarUrl ? (
<Image src={account.avatarUrl && `/image/${account.avatarUrl}`} className="img-thumbnail"
roundedCircle style={{ objectFit: "cover", width: "10rem", height: "10rem" }} />
) : (
<Image src={person} className="img-thumbnail"
roundedCircle style={{ objectFit: "cover", width: "10rem", height: "10rem" }} />
)}
</Button> </Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>이미지를 변경하시겠습니까?</Modal.Title>
</Modal.Header>
<Form onSubmit={handleSubmit}>
<Modal.Body>
<Form.Control type="file" name="avatar" onChange={handleChange} />
</Modal.Body>
<Modal.Footer>
<Col className="px-0">
<Button variant="outline-secondary" onClick={handleBasic}
className="d-flex justify-content-start"><small>기본이미지로</small></Button>
{/* 기본이미지로 보내기 */}
</Col>
<Button variant="secondary" onClick={handleClose}>취소</Button>
<Button variant="primary" type="submit" onClick={handleClose}>저장</Button>
</Modal.Footer>
</Form>
</Modal>
</Col> </Col>
<Col > <Col >
<Row className="mt-4 text-center"> <Row className="mt-4 text-center">
...@@ -134,8 +192,7 @@ function Account() { ...@@ -134,8 +192,7 @@ function Account() {
) )
}
}
export default Account export default Account
import React, { useState } from 'react'
import { Card, Image, Container, Row, Col, Table, Accordion, Button, Form } from 'react-bootstrap'
import { Link } from 'react-router-dom';
import person from '../person.svg';
import mypagetiger from '../mypagetiger.svg';
import axios from 'axios'
import catchErrors from '../utils/catchErrors';
import { isAuthenticated } from '../utils/auth';
const INIT_ACCOUNT = {
name: "",
avatar: { person }
}
function EditAccount() {
const [account, setAccount] = useState(INIT_ACCOUNT)
const [error, setError] = useState("")
const user = isAuthenticated()
const handleChange = (event) => {
const { name, value, files } = event.target
if (files) {
for (const file of files) {
console.log("name=", name, "value=", value, 'file=', file);
}
setAccount({ ...account, [name]: files })
} else {
console.log("name=", name, "value=", value);
setAccount({ ...account, [name]: value })
}
}
const handleSubmit = async (event) => {
event.preventDefault()
//form-data에 설정
const formData = new FormData()
formData.append('name', account.name)
formData.append('avatar', account.avatar[0])
//서버전송
try {
if (user) {
console.log(user)
const response = await axios.put(`/api/users/account/${user}`, formData)
}
} catch (error) {
catchErrors(error, setError)
}
}
return (
<Container className="px-3">
<h3 className="my-4 mx-3 font-weight-bold">My Page</h3>
<Card md={3} className="p-1 mb-4" style={{ background: '#F7F3F3' }}>
<Form onSubmit={handleSubmit}></Form>
<Row className="p-2">
<Col md={4} className="d-flex align-content-center justify-content-center">
<Button type="button" variant="outline-light">
<Image src={account.avatarUrl && `/image/${account.avatarUrl}`} roundedCircle className="img-thumbnail" width={"170rem"} />
</Button>
</Col>
<Col >
<Row className="mt-4 text-center">
<Col>
<h2>
<strong>{person.name}</strong> <small>님</small>
</h2>
</Col>
</Row>
<Row className="px-3">
<Card.Body className="p-2 text-center">
<h4><Link to="/">
<strong title="홈으로">
<Form.File id="exampleFormControlFile1" label="Example file input" />
<Image src={mypagetiger} width={"30rem"} roundedCircle className="img-thumbnail" >
</Image>KU#</strong>
</Link>
{/* 홈페이지로 돌아가기 */}
방문해주신 <em> {account.name}</em> 님,<br></br>
진심으로 환영합니다! 즐거운 쇼핑 되세요.</h4>
</Card.Body>
</Row>
<Row className="mr-1 text-muted d-flex justify-content-end">
<a href="mailto:shoppingmall_KU@korea.ac.kr">
<small title="메일보내기"> * 문의 : shoppingmall_KU@korea.ac.kr </small>
</a>
{/* 쇼핑몰 문의 메일보내기 */}
</Row>
</Col>
</Row>
</Card>
<Accordion>
<Row className="my-3 px-3">
<Table>
<thead className="text-center" style={{ background: '#F7F3F3' }}>
<tr>
<th scope="col">주문현황</th>
<th scope="col">배송중</th>
<th scope="col">배송완료</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">케이시앵글부츠(SH)</th>
<td>Mark</td>
<td>Otto</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
</tr>
<tr>
<th scope="row">3</th>
<td colspan="2">Larry the Bird</td>
</tr>
</tbody>
</Table>
</Row>
</Accordion>
</Container >
)
}
export default EditAccount
import axios from "axios" import axios from "axios"
export function handleLogin(userId){ export function handleLogin(userId) {
localStorage.setItem('loginStatus',userId) localStorage.setItem('loginStatus', userId)
} }
export async function handleLogout(){ export async function handleLogout() {
localStorage.removeItem('loginStatus') localStorage.removeItem('loginStatus')
await axios.get('/api/auth/logout') await axios.get('/api/auth/logout')
window.location.href='/' window.location.href = '/'
} }
export function isAuthenticated(){ export function isAuthenticated() {
const userId= localStorage.getItem('loginStatus') const userId = localStorage.getItem('loginStatus')
if(userId){ if (userId) {
return userId return userId
} else{ } else {
return false return false
} }
} }
\ No newline at end of file
...@@ -14,6 +14,7 @@ connectDb() ...@@ -14,6 +14,7 @@ connectDb()
const app = express(); const app = express();
app.use("/image", express.static("uploads/"))
app.use(express.json()); app.use(express.json());
app.use(cors()) app.use(cors())
......
...@@ -6,7 +6,7 @@ import multer from "multer"; ...@@ -6,7 +6,7 @@ import multer from "multer";
const uploadimg = multer({ dest: 'uploads/' }); const uploadimg = multer({ dest: 'uploads/' });
const imgUpload = uploadimg.fields([ const imgUpload = uploadimg.fields([
{ name: 'main_image', maxCount: 1 } { name: 'avatar', maxCount: 1 }
]) ])
const username = (req, res) => { const username = (req, res) => {
...@@ -14,14 +14,14 @@ const username = (req, res) => { ...@@ -14,14 +14,14 @@ const username = (req, res) => {
console.log(req.account) console.log(req.account)
} }
const userById = async (req, res, next, id) => { //순서가 정해져있음. const userById = async (req, res, next, id) => {
try { try {
const user = await User.findById(id) const user = await User.findById(id)
if (!user) { if (!user) {
res.status(404).send('사용자를 찾을 수 없습니다') res.status(404).send('사용자를 찾을 수 없습니다')
} }
req.account = user req.account = user
next() //함수 , 넥스트를 만나면 아래로 안내려가고 바로 리턴을 한다. 그리고 끝나는게 아니라 다음 미들웨어가 있으면 다음 미들웨어로 넘긴다. next()
} catch (error) { } catch (error) {
console.log(error); console.log(error);
res.status(500).send('사용자 아이디 검색 실패') res.status(500).send('사용자 아이디 검색 실패')
...@@ -62,11 +62,21 @@ const signup = async (req, res) => { ...@@ -62,11 +62,21 @@ const signup = async (req, res) => {
const update = async (req, res) => { const update = async (req, res) => {
console.log("req", req.body)
try { try {
const avatar = req.files['avatar'][0] if (req.body.avatar == '') {
user.avatarUrl = avatar.filename const user = req.account
const updateUser = await avatar.save() user.avatarUrl = req.body.avatar
res.json(updateUser) const updateUser = await user.save()
res.json(updateUser)
} else {
const avatar = req.files['avatar'][0]
const user = req.account
user.avatarUrl = avatar.filename
const updateUser = await user.save()
res.json(updateUser)
}
} catch (error) { } catch (error) {
console.log(error); console.log(error);
res.status(500).send('이미지 업데이트 실패') res.status(500).send('이미지 업데이트 실패')
......
...@@ -8,6 +8,8 @@ router.route('/signup') ...@@ -8,6 +8,8 @@ router.route('/signup')
router.route('/account/:userId') router.route('/account/:userId')
.get(userCtrl.username) .get(userCtrl.username)
.put(userCtrl.imgUpload, userCtrl.update)
router.param('userId', userCtrl.userById) router.param('userId', userCtrl.userById)
......
...@@ -34,6 +34,9 @@ const UserSchema = new mongoose.Schema({ ...@@ -34,6 +34,9 @@ const UserSchema = new mongoose.Schema({
required: true, required: true,
default: 'user', default: 'user',
enum: ['user', 'admin', 'root'] enum: ['user', 'admin', 'root']
},
avatarUrl: {
type: String
} }
}, { }, {
timestamps: true timestamps: true
......
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