Skip to content
Snippets Groups Projects
Commit 6ba24f58 authored by Hyun Woo Jeong's avatar Hyun Woo Jeong
Browse files

댓글 작성, 삭제 구현

parent 1c345b79
Branches hgb-wip
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;
}
......
......@@ -6,8 +6,6 @@ import moment from 'moment'
import userService from './data/userService.js';
import articleService from './data/articleService.js';
const __dirname = path.resolve();
export const router = express.Router();
......@@ -29,7 +27,6 @@ router.post("/upload", upload.array("img"), async function(req, res, next) {
if(!req.session.sessionid){
// 세션이 없엉
}
console.log("포스팅 '해줘'");
const inputTitle = req.body.title
const inputContent = req.body.content
......@@ -39,7 +36,6 @@ router.post("/upload", upload.array("img"), async function(req, res, next) {
const inputkeyword = req.body.keyword
const inputlat = req.body.latitude
const inputlng = req.body.longitude
// const currentTime = moment().format('YYYY-MM-DD HH:mm')
await articleService.createArticle({
title: inputTitle,
......@@ -68,22 +64,10 @@ router.get("/loadarticle", async (req, res) => {
console.log("세션 X")
}
const articles = await articleService.findAllArticle();
articles.forEach((article) => {
article.imageUrls.forEach(
(urls) => {
try{
//res.sendFile(path.join(__dirname, urls));
}
catch(err){
console.log(err)
}
});
});
res.send(JSON.stringify(articles));
});
router.get("/loadarticle/:id", async (req, res) => {
if(req.session.sessionid){
console.log("세션 O")
}
......@@ -94,4 +78,31 @@ router.get("/loadarticle/:id", async (req, res) => {
res.send(JSON.stringify(articles));
});
router.post("/comment/:id", async (req, res) => {
if(req.session.sessionid){
console.log("세션 O")
}
else {
console.log("세션 X")
}
const user = await userService.findUserByEmail(req.session.sessionid.email);
const data = {
content: req.body.content,
author: user._id
}
const articles = await articleService.createComment(req.params.id, data);
res.send(JSON.stringify(articles));
})
router.delete("/comment/:articleid/:commentid", async (req, res) => {
if(req.session.sessionid){
console.log("세션 O")
}
else {
console.log("세션 X")
}
const articles = await articleService.deleteComment(req.params.articleid, req.params.commentid);
res.send(JSON.stringify(articles));
});
export default router;
......@@ -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
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>
);
console.log(articleContext)
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;
......@@ -41,7 +41,7 @@ function Header({islogged, username}){
<img className="logo_image" alt="logo" src={logo}/>
</ButtonLink>
<ul>
<p>{userinfo?`${userinfo.name}님, 환영합니다`:'로그인하세요.'}</p>
<p>{islogged?`${userinfo.name}님, 환영합니다`:'로그인하세요.'}</p>
<ul className="menu_list">
<li><ButtonLink link='/'>Home</ButtonLink></li>
<li><ButtonLink link='/search'>검색</ButtonLink></li>
......
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';
......
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,81 +9,106 @@ 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);
}, []);
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)
})
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>
)
})
}
</>
const onTextChange = (e) => {
const {value} = e.target;
setInputComment(value);
}
)
}
else {
return(
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");
})
.catch(err => {
console.error(err);
});
};
if (article) {
return(
<>
<div className="introduction" style={{display: 'flex'}}>
<p>로딩준</p>
<MapLocator loc={{lat: article.latitude, lng: article.longitude}} keyword={article.keyword}></MapLocator>
<div>
<Article data={article}></Article>
<button>조와요</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/loadarticle/${id}`, // 통신할 웹문서
method: 'get', // 통신할 방식
});
return response;
}
async function requestLoadArticleById(id) {
const response = await axios({
url: `http://localhost:8080/post/loadarticle/${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