Commit af72d9ac authored by JeongYeonwoo's avatar JeongYeonwoo
Browse files

Profile Page

parent f4bae50f
node_modules
package-lock.json
\ No newline at end of file
package-lock.json
package.json
uploads/
\ No newline at end of file
......@@ -25,4 +25,5 @@ yarn-error.log*
.env
.eslintcache
.package-lock.json
.package.json
debug.log
......@@ -2,6 +2,7 @@
"name": "client",
"version": "0.1.0",
"private": true,
"type": "module",
"dependencies": {
"@testing-library/jest-dom": "^5.11.6",
"@testing-library/react": "^11.2.2",
......
......@@ -69,10 +69,10 @@ function Home() {
const sendMsg = (e) => {
e.preventDefault()
socket.emit("chat", {
roomName: roomName,
msg: inner,
});
// socket.emit("chat", {
// roomName: roomName,
// msg: inner,
// });
}
useEffect(() => {
......
......@@ -3,35 +3,36 @@ import Menu from '../Components/Menu';
import { Image, Button, Container, Form, Row, Col, Dropdown } from 'react-bootstrap';
import { BrowserRouter as Link } from 'react-router-dom';
import axios from 'axios'
import catchErrors from '../utils/catchErrors'
import { isAuthenticated } from '../utils/auth';
import userdefault from '../Images/KakaoTalk_20201230_153151693.png'
import img1 from '../Images/img_1.png'
import img2 from '../Images/img_2.png'
import img3 from '../Images/img_3.jpg'
import DropdownItem from 'react-bootstrap/esm/DropdownItem';
// const INIT_USER = {
// username: '',
// email: '',
// nickname: ''
// }
const INIT_USER = {
username: '',
email: '',
nickname: '',
imageUrl: []
}
function ProfilePage() {
const [user, setUser] = useState('')
const [user, setUser] = useState(INIT_USER)
const [error, setError] = useState('')
const [userimg, setUserimg] = useState(img2)
const [defaultImg, setDefaultImg] = useState(true)
const [hidden, setHidden] = useState(true)
const [changed, setChanged] = useState(false)
const userId = isAuthenticated()
async function getLoginedUser() { //email로 db에서 찾아오기 ㅇㅇㅇㅇㅇ
const userid = sessionStorage.getItem('userId')
const response = await axios.post(`/users/${userid}`, { '_id': userid })
setUser(response.data)
async function getProfile(userId) {
try {
const response = await axios.get(`/users/${userId}`)
setUser(response.data)
} catch (error) {
catchErrors(error, setError)
}
}
function handleSubmit(e) {
function handleSubmitHidVis(e) {
e.preventDefault()
if (hidden) {
setHidden(false)
......@@ -40,70 +41,62 @@ function ProfilePage() {
}
}
function handleChange(e) {
setUser({ ...user, 'nickname': e.target.value })
}
async function handleNicksave() {
const userid = sessionStorage.getItem('userId')
await axios.put(`/users/${userid}`, user)
}
function setThumbnail(event) { //불러온 사진 <div id='image_container'>에 띄우기
let reader = new FileReader();
reader.onload = function (event) {
let img = document.createElement("img");
img.setAttribute("src", event.target.result);
img.setAttribute("id", "profileImg")
img.setAttribute("style", 'height:300px; width:300px')
img.setAttribute("class", "mb-3")
// img.setAttribute("class","d-flex justify-content-center mb-3")
document.querySelector("div#image_container").appendChild(img);
};
reader.readAsDataURL(event.target.files[0]);
if (defaultImg) { //첫 이미지 업로드(default이미지 지우고 유저가 올린걸로 업로드)
let del = document.getElementById("defaultImg")
del.remove()
setDefaultImg(false)
const { name, value, files } = e.target
if (files) {
setUser({ ...user, [name]: files })
} else {
setUser({ ...user, [name]: value })
}
else { //기존에 올렸던 사진 지우고 재선택한 사진 업로드
let del2 = document.getElementById('profileImg')
del2.remove()
reader.onload = function (event) {
let img = document.createElement("img");
img.setAttribute("src", event.target.result);
img.setAttribute("id", "profileImg")
img.setAttribute("style", 'height:300px; width:300px')
document.querySelector("div#image_container").appendChild(img);
};
setChanged(true)
}
async function handleSubmit(e) {
e.preventDefault()
if (changed) {
const formData = new FormData()
formData.append('imageUrl', user.imageUrl[0])
formData.append('newNickname', user.nickname)
try {
if (userId && user.imageUrl) {
await axios.put(`/users/${userId}`, formData)
alert('저장되었습니다.')
window.location.reload()
}
// else{
// console.log("삐빅")
// const formData = new FormData()
// formData.append('newNickname', user.nickname)
// const response = await axios.put(`/users/${userId}`, formData)
// }
} catch (error) {
catchErrors(error, setError)
}
} else {
alert('변경사항이 없습니다.')
}
}
useEffect(() => {
getLoginedUser()
console.log(user)
}, [])
getProfile(userId)
}, [userId])
return (
<div>
<>
<Menu />
<Container className='border' fluid>
<Row>
<Col sm={4}>
<Row className='justify-content-center'>
<div className="d-flex ml-3 mt-3" id="defaultImg">
<Image src={userimg} width="300px" roundedCircle />
</div>
{user.profileimg ? <Image src={user.profileimg && `/images/${user.profileimg}`} style={{ width: "300px", height: "300px" }} roundedCircle /> : <Image src='https://www.flaticon.com/svg/vstatic/svg/149/149071.svg?token=exp=1610922596~hmac=f4b972b9db509d4e3cc2eb40543b0b0f' style={{ width: "300px", height: "300px" }} roundedCircle /> }
</Row>
<Row className='ml-3 mt-3 justify-content-center'>
<Form className="d-flex">
<Form.Group>
<div id="image_container"></div>
<Form.File label="프로필 사진 변경" accept="image/*" onChange={setThumbnail} />
<Form.Label>프로필 사진 변경</Form.Label>
<Form.Control type='file' name='imageUrl' onChange={handleChange} />
</Form.Group>
</Form>
</Row>
<Row className="d-flex justify-content-center mb-3">
{/* <Row className="d-flex justify-content-center mb-3">
<Dropdown>
<Dropdown.Toggle variant='success' id='dropdown-basic'>
프로필 사진 선택
......@@ -114,7 +107,7 @@ function ProfilePage() {
<Dropdown.Item href='/'>어피치</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</Row>
</Row> */}
</Col>
<Col sm={8}>
<Row className='m-5 justify-content-center'>
......@@ -123,7 +116,6 @@ function ProfilePage() {
<Row className="m-3 justify-content-flex-start" style={{ fontWeight: "bold", fontSize: "large" }}>
<Col xs={3}>이름 :</Col>
<Col xs={6}>{user.username}</Col>
{/* <Col sm={4}></Col> */}
</Row>
<Row className="m-3 justify-content-flex-start" id="nickname" style={{ fontWeight: "bold", fontSize: "large" }}>
<Col xs={3}>별명 :</Col>
......@@ -132,11 +124,11 @@ function ProfilePage() {
</Col>
<Col xs={6} hidden={hidden}>
<Form>
<Form.Control defaultValue={user.nickname} style={{ width: "110%" }} onChange={handleChange} />
<Form.Control defaultValue={user.nickname} name='nickname' style={{ width: "110%" }} onChange={handleChange} />
</Form>
</Col>
<Col xs={3}>
<Form className="d-flex" onSubmit={handleSubmit}>
<Form className="d-flex" onSubmit={handleSubmitHidVis}>
<Button className="ml-3 d-flex justify-content-end" variant="outline-primary" size="sm" type='submit'>수정</Button>
</Form>
</Col>
......@@ -146,8 +138,8 @@ function ProfilePage() {
<Col xs={6}>{user.email}</Col>
</Row>
<Row className='m-3 justify-content-center'>
<Form>
<Button variant="outline-success" size="sm" className="mr-4" onClick={handleNicksave}>저장</Button>
<Form onSubmit={handleSubmit}>
<Button variant="outline-success" size="sm" className="mr-4" type='submit'>저장</Button>
<Link to='/'>
<Button variant="outline-success" size="sm" className="ml-4" > 화면으로</Button>
</Link>
......@@ -156,7 +148,7 @@ function ProfilePage() {
</Col>
</Row>
</Container>
</div>
</>
)
}
......
......@@ -4,6 +4,14 @@ import isEmail from 'validator/lib/isEmail.js'
import bcrypt from "bcryptjs";
import jwt from 'jsonwebtoken'
import config from "../config.js"
import multer from "multer";
import catchErrors from "../../client/src/utils/catchErrors.js";
const upload = multer({ dest: 'uploads/' })
const profileUpload = upload.fields([
{ name: 'imageUrl', maxCount: 1 },
])
const signup = async (req, res) => {
......@@ -33,38 +41,48 @@ const signup = async (req, res) => {
email,
password: hash,
}).save()
console.log(newUser)
res.json(newUser)
} catch (error) {
//알수없는 모든 에러발생시 처리
console.log(error)
res.status(500).send('회원가입 에러발생하였습니다.')
}
}
const hello = async (req, res) => {
let users = await User.find().select('name nickname email _id').exec()
return res.json(users)
}
const logineduser = async (req, res) => {
const update = async (req, res) => {
const username = req.user.username
const newNickname = req.body.newNickname
try {
let user = await User.findOne(req.body).select('username email nickname').exec()
return res.json(user)
await User.updateOne({ 'username': username }, { 'nickname': newNickname })
const imageUrl = req.files['imageUrl'][0]
const user = req.user
user.profileimg = imageUrl.filename //우리가 사용할 uesr.profileimg에다가 imageUrl의 filename을 저장
const updatedUser = await user.save()
res.json(updatedUser)
} catch (error) {
alert('올바르지 못한 접근입니다.')
console.log(error)
res.status(500).send('프로필 업데이트 실패')
}
}
const changenick = async (req, res) => {
const userById = async (req, res, next, id) => { //id로 찾아와서 req.user를 우리가 찾는 user로 저장
try {
const newnick = req.body.nickname
await User.update({ 'username': req.body.username }, { 'nickname': newnick })
const user = await User.findById(id)
if (!user) {
res.status(404).send('사용자를 찾을 수 없습니다.')
}
req.user = user
next()
} catch (error) {
alert('올바르지 못한 접근입니다.')
console.log(error)
res.status(500).send('사용자 아이디 검색 실패')
}
}
const getProfile = (req, res) => {
res.json(req.user)
}
export default { signup, hello, logineduser, changenick }
export default { signup, profileUpload, update, userById, getProfile }
// {} : 객체로 return함
\ No newline at end of file
......@@ -29,7 +29,10 @@ const UserSchema = new mongoose.Schema({
//정보를 찾을때 찾지 않게함
//플러스 옵션을 주면 찾을 수 있음(mongoose에서 용법찾아봐야됨)
},
},{
profileimg: {
type: String
},
}, {
//옵셥을 정의함.
timestamps: true
//기본이 false로 되어있음
......
......@@ -6,11 +6,12 @@ const router = express.Router()
router.route('/users/signup')
.post(userCtrl.signup)
.get(userCtrl.hello)
router.route(`/users/:userId`)
.post(userCtrl.logineduser)
.put(userCtrl.changenick)
.get(userCtrl.getProfile)
.put(userCtrl.profileUpload, userCtrl.update)
router.param('userId', userCtrl.userById)
export default router
\ No newline at end of file
......@@ -40,6 +40,7 @@ io.on("connection", (socket) => { // 기본 연결
app.use(bodyParser.json());
app.use(cors());
app.use('/images', express.static('uploads/'))
app.use(userRouter)
app.use(authRouter)
app.use(roomRouter)
......
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