Skip to content
Snippets Groups Projects
Commit 14c7e863 authored by Gwangbin's avatar Gwangbin
Browse files
parents 2c0709d0 2892e0e9
No related branches found
No related tags found
No related merge requests found
......@@ -62,7 +62,7 @@ const articleService = {
const article = await Article.findById(articleId);
article.comments.push(commentData);
await article.save();
return article;
return article.populate('author');
} catch (err) {
throw err;
}
......@@ -73,7 +73,7 @@ const articleService = {
const article = await Article.findById(articleId);
article.comments.pull({ _id: commentId });
await article.save();
return article;
return article.populate('author');
} catch (err) {
throw err;
}
......
......@@ -31,7 +31,7 @@ router.post('/login', async (req, res) => {
console.log('login done')
req.session.sessionid = req.body; //프론트에서 건네받은 JWT로 세션 생성
res.cookie('name', req.body.name, {expires}); //사용자 이름 쿠키
res.cookie('name', JSON.stringify({name:req.body.name, id:req.body.email}), {expires}); //사용자 이름 쿠키
res.send(req.body.name); // 이름 보내서 뭐하게?
......
import "./css/App.css";
import {Routes, Route, Link, useNavigate, Navigate } from 'react-router-dom';
import React, { useEffect, useState, useContext} from 'react';
import cookie from 'react-cookies';
import { UserContext } from './Context.js';
import Main from "./pages/Main.js";
......@@ -22,6 +24,8 @@ function App() {
function MoveTo(link){
navigate(link)
}
const userinfo = cookie.load('name')
// 헤더 업데이트
const LogIn = (name)=>{
// API 로그아웃 요청
......@@ -60,7 +64,7 @@ function App() {
return(
<div className="App">
<UserContext.Provider value={{isloggedIn, userName, LogIn, LogOut, CheckSession}}>
<Header islogged={isloggedIn} username={userName}></Header>
<Header cookie={userinfo} username={userName}></Header>
<Routes>
<Route path="/" element={<Main/>}></Route>
<Route path="/login" element={<Login/>}></Route>
......
......@@ -8,8 +8,8 @@ const UserContext = createContext({
CheckSession : ()=>{}
});
const LocationContext = createContext({
const ArticleContext = createContext({
Aritcle: {}
});
export {UserContext, LocationContext}
\ No newline at end of file
export {UserContext, ArticleContext}
\ No newline at end of file
......@@ -20,8 +20,8 @@ function Article({ data }) {
// http://localhost:8080/uploads/21701487062905.png
return (
<img
src={`http://localhost:8080/${el.replaceAll("\\", "/").substring(7)}`}
alt={`http://localhost:8080/${el.replaceAll("\\", "/").substring(7)}`}
src={`http://localhost:8080/${el.replaceAll("\\", "/").substring(5)}`}
alt={`http://localhost:8080/${el.replaceAll("\\", "/").substring(5)}`}
style={{ width: "100px", height: "100px" }} />
)
});
......
import React, {useEffect, useState} from "react";
import "../css/Article.css"
import {Routes, Route, Link, useNavigate, Navigate } from 'react-router-dom';
import { useParams } from 'react-router-dom';
import React, { useEffect, useState, useContext} from 'react';
import cookie from 'react-cookies';
import {Routes, Route, Link, useNavigate, Navigate, useParams } from 'react-router-dom';
import { UserContext, ArticleContext } from '../Context.js';
import { DateTime } from 'luxon';
import axios from 'axios';
axios.defaults.withCredentials = true;
function Comments({data}) {
const {
_id, content, author, createdAt} = data;
let params = useParams();
const navigate = useNavigate();
function MoveTo(link){
navigate(link)
}
const articleContext = useContext(ArticleContext);
const userinfo = cookie.load('name')
const date = DateTime.fromISO(createdAt).toFormat('yyyy년 MM월 dd일 HH:mm');
return (
<div class="comment">
<p>{author.nickname}</p>
<p>{content}</p>
<p>{date}</p>
</div>
);
function DeleteComment(e) {
const data = {id: _id}
axios
.delete(`http://localhost:8080/post/comment/${params.id}/${_id}`, data,
{
headers: {"Content-Type": 'application/json'}
})
.then(res => {
alert("The comment is successfully deleted");
return articleContext.requestLoadArticleById(params.id)
})
.then(res => {
articleContext.setArticle(res.data)
})
.catch(err => {
console.error(err);
});
};
if (userinfo.id===author.email) {
return (
<div class="comment" style={{display: 'flex'}}>
<p>{author.nickname}</p>
<p>{content}</p>
<p>{date}</p>
<button style={{height: '30px'}} onClick={DeleteComment} type="submit">지우기</button>
</div>
);
}
else {
return (
<div class="comment" style={{display: 'flex'}}>
<p>{author.nickname}</p>
<p>{content}</p>
<p>{date}</p>
</div>
);
}
}
export default Comments;
......@@ -5,20 +5,8 @@ import { UserContext } from '../Context.js';
import React, { useEffect, useState, useContext} from 'react';
import { Link, useNavigate, Navigate } from "react-router-dom";
import cookie from 'react-cookies';
import {useCookies} from 'react-cookie'
function Welcome(props){
return (
<p>
{props.name?`${props.name}님, 환영합니다`:'로그인하세요.'}<br/>
</p>
)
}
function ButtonLink({link, status, children}){
const userContext = useContext(UserContext);
......@@ -29,35 +17,42 @@ function ButtonLink({link, status, children}){
if (status) {
return (
<botton onClick = {()=>{userContext.LogOut()}}>
{children}
</botton>
<div>
<label className='Labelheader' htmlFor={children}>{children}</label>
<button id={children} onClick = {()=>{userContext.LogOut()}} style={{ display: "none"}}>
{children}
</button>
</div>
)
}
else {
return (
<botton onClick = {()=>{MoveTo(link)}}>
{children}
</botton>
<div>
<label className='Labelheader' htmlFor={children}>{children}</label>
<button id={children} onClick = {()=>{MoveTo(link)}} style={{ display: "none"}}>
{children}
</button>
</div>
)
}
}
function Header({islogged, username}){
const name = cookie.load('name')
function Header({cookie}){
return(
<div className="header">
<ButtonLink link='/'>
<img className="logo_image" alt="logo" src={logo}/>
</ButtonLink>
<ul>
<p>{name?`${name}님, 환영합니다`:'로그인하세요.'}</p>
<p>{cookie?`${cookie.name}님, 환영합니다`:'로그인하세요.'}</p>
<ul className="menu_list">
<li><ButtonLink link='/'>Home</ButtonLink></li>
<li><ButtonLink link='/search'>검색</ButtonLink></li>
<li><ButtonLink link='/postwrite'>포스트 작성</ButtonLink></li>
<li><ButtonLink link={islogged?'/':'/login'} status={islogged}>{islogged?'로그아웃':'로그인'}</ButtonLink></li> {/*로그인 여부 로직 구현 필요*/}
<li><ButtonLink link={cookie?'/':'/login'} status={cookie?true:false}>{cookie?'로그아웃':'로그인'}</ButtonLink></li> {/*로그인 여부 로직 구현 필요*/}
{/* { Object.keys(user).length != 0 ?
<li><Link to={`/profile/${getUserId()}`}>profile</Link>/<span onClick={logout}>logout</span></li> :
<li><Link to="/login">login</Link></li>
......
......@@ -32,4 +32,14 @@ li{
margin-right: 3rem;
font-size: 1.2rem;
font-weight: 100;
}
.Labelheader{
font-size: xx-large;
color: #FF7002;
font-weight: bold;
}
.Labelheader:hover{
color: #a5500f;
}
\ No newline at end of file
import { useNavigate } from 'react-router-dom';
import cookie from 'react-cookies';
import { UserContext } from '../Context.js';
import Article from '../components/Article.js';
import React, { useEffect, useState, useContext} from 'react';
......@@ -52,7 +52,11 @@ function Main() {
async function requestLoadArticle() {
const response = await axios({
<<<<<<< HEAD
url: 'http://localhost:8080/article', // 통신할 웹문서
=======
url: 'http://localhost:8080/post/article', // 통신할 웹문서
>>>>>>> 2892e0e9c9dd1752080a370ba274deeca6254246
method: 'get', // 통신할 방식
});
return response;
......
import { useNavigate } from 'react-router-dom';
import { useParams } from 'react-router-dom';
import { useNavigate, useParams } from 'react-router-dom';
import React, { useEffect, useState, useContext} from 'react';
import Article from '../components/Article.js';
import { UserContext } from '../Context.js';
import { UserContext, ArticleContext } from '../Context.js';
import MapLocator from '../components/MapForLoaction.js';
import Comment from '../components/Comment.js';
......@@ -10,75 +9,55 @@ import axios from 'axios';
axios.defaults.withCredentials = true;
function PostRead() {
let params = useParams();
const userContext = useContext(UserContext);
const [article, setArticle] = useState(null)
const navigate = useNavigate();
function MoveTo(link){
navigate(link)
}
useEffect(() => {
userContext.CheckSession()
.then((response) => {
if (!response.data) {
alert("세션이 만료되었습니다. 다시 로그인 바랍니다.")
MoveTo('/login')
}
else{
return requestLoadArticleById(params.id)
}
})
.then((response) => {
console.log(response)
setArticle(response.data)
})
.catch((response)=>{
console.log("error!:LogOut")
console.log(response)
})
let params = useParams();
const userContext = useContext(UserContext);
const articleContext = useContext(ArticleContext);
}, []);
console.log(article);
console.log(article?Object.values(article):"no");
if (article) {
return(
<>
<div className="introduction" style={{display: 'flex'}}>
<MapLocator loc={{lat: article.latitude, lng: article.longitude}} keyword={article.keyword}></MapLocator>
<div>
<Article data={article}></Article>
<button>조와요</button>
</div>
</div>
<form>
<div style={{display: 'flex'}}>
<button>댓글 작성</button>
<input type="text"></input>
</div>
</form>
{
article.comments.map((el)=>{
return(
<Comment key={el._id} data={el}></Comment>
)
})
}
</>
)
}
else {
return(
<div className="introduction" style={{display: 'flex'}}>
<p>로딩준</p>
</div>
)
const [article, setArticle] = useState(null)
const [inputComment, setInputComment] = useState("")
const [commentList, setCommentList] = useState("")
const navigate = useNavigate();
function MoveTo(link){
navigate(link)
}
useEffect(() => {
userContext.CheckSession()
.then((response) => {
if (!response.data) {
alert("세션이 만료되었습니다. 다시 로그인 바랍니다.")
MoveTo('/login')
}
else{
return requestLoadArticleById(params.id)
}
})
.then((response) => {
console.log(response)
setArticle(response.data)
})
.catch((response)=>{
console.log("error!:LogOut")
console.log(response)
})
}, []);
function SetLike(){
axios.put(`http://localhost:8080/post/comment/like/${params.id}`)
.then(res => {
alert("The comment is successfully uploaded");
return requestLoadArticleById(params.id)
})
.then(res => {
setArticle(res.data)
})
.catch(err => {
console.error(err);
});
}
<<<<<<< HEAD
async function requestLoadArticleById(id) {
const response = await axios({
url: `http://localhost:8080/article/${id}`, // 통신할 웹문서
......@@ -86,5 +65,79 @@ function PostRead() {
});
return response;
}
=======
const onTextChange = (e) => {
const {value} = e.target;
setInputComment(value);
}
>>>>>>> 2892e0e9c9dd1752080a370ba274deeca6254246
const onSubmit = e => {
e.preventDefault();
if (!inputComment) {
alert("댓글을 작성해주세요.");
return
}
const data = {content: inputComment}
axios.post(`http://localhost:8080/post/comment/${params.id}`, data,
{
headers: {"Content-Type": 'application/json'}
})
.then(res => {
alert("The comment is successfully uploaded");
return requestLoadArticleById(params.id)
})
.then(res => {
setArticle(res.data)
})
.catch(err => {
console.error(err);
});
};
if (article) {
return(
<>
<div className="introduction" style={{display: 'flex'}}>
<MapLocator loc={{lat: article.latitude, lng: article.longitude}} keyword={article.keyword}></MapLocator>
<div>
<Article data={article}></Article>
<button onClick={SetLike}>조와요</button>
</div>
</div>
<form onSubmit={onSubmit}>
<div style={{display: 'flex'}}>
<button>댓글 작성</button>
<input type="text" onChange={onTextChange}></input>
</div>
</form>
<ArticleContext.Provider value={{requestLoadArticleById, setArticle}}>
{
article.comments.map((el)=>{
return(
<Comment key={el._id} data={el}></Comment>
)
})
}
</ArticleContext.Provider>
</>
)
}
else {
return(
<div className="introduction" style={{display: 'flex'}}>
<p>로딩준</p>
</div>
)
}
}
async function requestLoadArticleById(id) {
const response = await axios({
url: `http://localhost:8080/post/article/${id}`, // 통신할 웹문서
method: 'get', // 통신할 방식
});
return response;
}
export default PostRead;
\ No newline at end of file
export default PostRead;
\ No newline at end of file
import React, { useRef, useState, useEffect, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { UserContext } from '../Context.js';
import SearchMap from '../components/SearchMapByKeyword.js'
......
......@@ -5,40 +5,6 @@ import SearchMap from '../components/SearchMapByKeyword.js'
import { UserContext } from '../Context.js';
const {kakao} = window;
//카카오 지도 API를 이용한 검색(예정)
/*
function SearchMap(props){
// 아주대학교를 기본 위치로 설정
const [state, setState] = useState({
center: { lat: 37.28238488648025, lng: 127.04350967609274 },
isPanto: true,
});
const [searchAddress, SetSearchAddress] = useState(); //주소 입력
const handleInput = (e) => {
SetSearchAddress(e.target.value);
}
const SearchStart = () => {
console.log('Start Search!');// action test
// 주소를 기반으로 한 검색 구현(제주특별자치도 제주시 첨단로 242 를 입력하면 kakao가 나온다)
const geocoder = new kakao.maps.services.Geocoder();
let callback = function(result, status) {
if (status === kakao.maps.services.Status.OK) {
const newSearch = result[0]
setState({
center: { lat: newSearch.y, lng: newSearch.x }
})
}
};
geocoder.addressSearch(`${searchAddress}`, callback);
}
}
*/
function Search(props) {
const userContext = useContext(UserContext);
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment