edit 부분에 질문이 있습니다.
370
投稿した質問数 5
edit 부분에 질문이 있습니다. 이렇게 수정버튼을 누르면 제목과 내용은 로딩이 되는데
이미지 부분만이 로딩이 안되어서 질문을 드립니다.
post js
var express = require("express");
var router = express.Router();
const multer = require("multer");
const { Post } = require("../Model/Post.js");
const { Counter } = require("../Model/Counter.js");
const { User } = require("../Model/User.js");
const setUpload = require("../Util/upload.js");
router.post("/submit", (req, res) => {
let temp = {
title: req.body.title,
content: req.body.content,
image: req.body.image,
};
Counter.findOne({ name: "counter" })
.exec()
.then((counter) => {
temp.postNum = counter.postNum;
User.findOne({ uid: req.body.uid })
.exec()
.then((userInfo) => {
temp.author = userInfo._id;
const CommunityPost = new Post(temp);
CommunityPost.save().then((doc) => {
Counter.updateOne(
{ name: "counter" },
{ $inc: { postNum: 1 } }
).then(() => {
res.status(200).json({ success: true });
});
});
});
})
.catch((err) => {
res.status(400).json({ success: false });
});
});
router.post("/list", (req, res) => {
let sort = {};
if (req.body.sort === "최신순") {
sort.createdAt = -1;
} else {
//인기순
sort.repleNum = -1;
}
Post.find({
$or: [
{ title: { $regex: req.body.searchTerm } },
{ content: { $regex: req.body.searchTerm } },
],
})
.populate("author")
.sort(sort)
.skip(req.body.skip) // 0, 5
.limit(5) //한번에 찾을 doc 숫자
.exec()
.then((doc) => {
res.status(200).json({ success: true, postList: doc });
})
.catch((err) => {
res.status(400).json({ success: false });
});
});
router.post("/detail", (req, res) => {
Post.findOne({ postNum: Number(req.body.postNum) })
.populate("author")
.exec()
.then((doc) => {
res.status(200).json({ success: true, post: doc });
})
.catch((err) => {
res.status(400).json({ success: false });
});
});
router.post("/edit", (req, res) => {
let temp = {
title: req.body.title,
content: req.body.content,
image: req.body.image,
};
Post.updateOne({ postNum: Number(req.body.postNum) }, { $set: temp })
.exec()
.then(() => {
res.status(200).json({ success: true });
})
.catch((err) => {
res.status(400).json({ success: false });
});
});
router.post("/delete", (req, res) => {
Post.deleteOne({ postNum: Number(req.body.postNum) })
.exec()
.then(() => {
res.status(200).json({ success: true });
})
.catch((err) => {
res.status(400).json({ success: false });
});
});
/*
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "image/");
},
filename: function (req, file, cb) {
cb(null, `${Date.now()}_${file.originalname}`);
},
});
const upload = multer({ storage: storage }).single("file");
router.post("/image/upload", (req, res) => {
upload(req, res, (err) => {
if (err) {
res.status(400).json({ success: false });
} else {
res.status(200).json({ success: true, filePath: res.req.file.path });
}
});
});
*/
router.post(
"/image/upload",
setUpload("react-community/post"),
(req, res, next) => {
res.status(200).json({ success: true, filePath: res.req.file.location });
}
);
module.exports = router;
edit js
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import ImageUpload from "./ImageUpload.js";
import { useNavigate } from "react-router-dom";
//
import {
UploadButtonDiv,
UploadDiv,
UploadForm,
} from "../../Style/UploadCSS.js";
function Edit() {
let navigate = useNavigate();
let params = useParams();
const [PostInfo, setPostInfo] = useState([]);
const [Flag, setFlag] = useState(false);
const [Title, setTitle] = useState("");
const [Content, setContent] = useState("");
const [Image, setImage] = useState("");
useEffect(() => {
setTitle(PostInfo.title);
setContent(PostInfo.content);
setImage(PostInfo.image);
console.log(PostInfo.image);
}, [PostInfo]);
useEffect(() => {
let body = {
postNum: params.postNum,
};
axios
.post("/api/post/detail", body)
.then((response) => {
if (response.data.success) {
setPostInfo(response.data.post);
setFlag(true);
}
})
.catch((err) => {
console.log(err);
});
}, []);
const onSubmit = (e) => {
e.preventDefault();
if (Title === "" || Content === "") {
return alert("모든 항목을 채워 주십쇼");
}
let body = {
title: Title,
content: Content,
image: Image,
postNum: params.postNum,
};
axios
.post("/api/post/edit", body)
.then((response) => {
if (response.data.success) {
alert("글 수정이 완료되었습니다.");
navigate(`/post/${params.postNum}`);
} else {
alert("글 수정에 실패하였습니다.");
}
})
.catch((err) => {
console.log(err);
});
};
return (
<UploadDiv>
{Flag && (
<UploadForm>
<label htmlFor="label">제목</label>
<input
id="title"
type="text"
value={Title}
onChange={(e) => {
setTitle(e.currentTarget.value);
}}
/>
<ImageUpload setImage={setImage} />
<label htmlFor="content">내용</label>
<textarea
id="content"
value={Content}
onChange={(e) => {
setContent(e.currentTarget.value);
}}
/>
<UploadButtonDiv>
<button
className="cancel"
onClick={(e) => {
e.preventDefault();
navigate(-1);
}}
>
취소
</button>
<button
onClick={(e) => {
onSubmit(e);
}}
>
제출
</button>
</UploadButtonDiv>
</UploadForm>
)}
</UploadDiv>
);
}
export default Edit;
detail js
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { useParams, useNavigate } from "react-router-dom";
import axios from "axios";
import Spinner from "react-bootstrap/Spinner";
import {
PostDiv,
Post,
BtnDiv,
SpinnerDiv,
} from "../../Style/PostDetailCSS.js";
function Detail() {
let navigate = useNavigate();
let params = useParams();
const [PostInfo, setPostInfo] = useState([]);
const [Flag, setFlag] = useState(false);
useEffect(() => {
let body = {
postNum: params.postNum,
};
axios
.post("/api/post/detail", body)
.then((response) => {
console.log(response);
if (response.data.success) {
setPostInfo(response.data.post);
setFlag(true);
}
})
.catch((err) => {
console.log(err);
});
}, []);
useEffect(() => {
console.log(PostInfo);
}, [PostInfo]);
const DeleteHandler = () => {
if (window.confirm("정말로 삭제를 하시겠습니까?")) {
let body = {
postNum: params.postNum,
};
axios
.post("/api/post/delete", body)
.then((response) => {
if (response.data.success) {
alert("게시글이 삭제 되었습니다.");
navigate("/");
}
})
.catch((err) => {
alert("게시글이 삭제에 실패하였습니다.");
});
}
};
return (
<PostDiv>
{Flag ? (
<>
<Post>
<h1>{PostInfo.title}</h1>
{PostInfo.image ? (
<img
src={`http://localhost:5000/${PostInfo.image}`}
alt=""
style={{ width: "100%", height: "auto" }}
/>
) : null}
<p>{PostInfo.content}</p>
</Post>
<BtnDiv>
<Link to={`/edit/${PostInfo.postNum}`}>
<button className="edit">수정</button>
</Link>
<button className="delete" onClick={() => DeleteHandler()}>
삭제
</button>
</BtnDiv>
</>
) : (
<SpinnerDiv>
<Spinner animation="border" role="status">
<span className="visually-hidden">Loading...</span>
</Spinner>
</SpinnerDiv>
)}
</PostDiv>
);
}
export default Detail;
imageupload
import React from "react";
import { Form } from "react-bootstrap";
import axios from "axios";
function ImageUpload(props) {
const FileUpload = (e) => {
var formData = new FormData();
formData.append("file", e.target.files[0]);
axios.post("/api/post/image/upload", formData).then((response) => {
props.setImage(response.data.filePath);
});
};
return (
<div>
<Form.Control
type="file"
className="shadow-none"
accept="image/*"
onChange={(e) => FileUpload(e)}
/>
</div>
);
}
export default ImageUpload;
upload js
import React, { useState, useEffect } from "react";
import ImageUpload from "./ImageUpload.js";
import {
UploadButtonDiv,
UploadDiv,
UploadForm,
} from "../../Style/UploadCSS.js";
import axios from "axios";
import { useNavigate } from "react-router-dom";
function Upload(props) {
const [Title, setTitle] = useState("");
const [Content, setContent] = useState("");
const [Image, setImage] = useState("");
let navigate = useNavigate();
const onSubmit = (e) => {
e.preventDefault();
if (Title === "" || Content === "") {
return alert("모든 항목을 채워 주십쇼");
}
let body = {
title: Title,
content: Content,
image: Image,
};
axios
.post("api/post/submit", body)
.then((response) => {
console.log(response);
if (response.data.success) {
alert("글 작성이 완료되었습니다.");
navigate("/");
} else {
alert("글 작성에 실패하였습니다.");
}
})
.catch((err) => {
console.log(err);
});
};
return (
<UploadDiv>
<UploadForm>
<label htmlFor="label">제목</label>
<input
id="title"
type="text"
value={Title}
onChange={(e) => {
setTitle(e.currentTarget.value);
}}
/>
<ImageUpload setImage={setImage} />
<label htmlFor="content">내용</label>
<textarea
id="content"
value={Content}
onChange={(e) => {
setContent(e.currentTarget.value);
}}
/>
<UploadButtonDiv>
<button
button
onClick={(e) => {
onSubmit(e);
}}
>
제출
</button>
</UploadButtonDiv>
</UploadForm>
</UploadDiv>
);
}
export default Upload;
回答 1
0
axios .post("/api/post/detail", body) .then((response) => { if (response.data.success) { setPostInfo(response.data.post); setFlag(true); } }) .catch((err) => { console.log(err); });
수정버튼을 눌렀을때 이미지가 안보인단 말씀이시죠~?
위 코드에서 response에 담겨져있는 값을 확인해보셨을까요?
Heroku 데이터로드 문제.
0
182
2
몽고DB
0
168
1
No routes matched location Error Component Stack error 질문입니다.
0
578
1
axios 문제 404에러
0
2113
1
도와주세요
0
456
3
네이버 클라우드를 사용하지 않는 사람은 외부저장소~env 까지 따라하지 않아도 되죠?
0
236
0
두번씩 실행되는 문제..
0
462
1
스타일 깃허브에서 코드 가져가라고 하셨는데요
0
465
2
read(2) 강의 내용에 질문이 있습니다.
0
265
1
깃허브
0
347
1
마지막에 "" 로 채워주는 이유가 있을까요?
0
284
1
React-router-dom을 설치하고 react app이 크롬에서 실행되지 않습니다.
0
379
1
Detail.js CSS 관련 강의가 없어진거 같은데요 ?
0
280
1
504 에러
0
852
1
콘솔에 DOM이라는 로그가 뜨는데
0
286
1
useEffect 두번 사용하는 것
0
927
1
작동은 잘되는데 오류가 뜹니다
0
439
1
react-router-dom 현재 최신버전
0
613
1
Test.js 소스코드 볼 수 있을까요?
0
489
2
닉네임 중복검사 시 404 에러
0
506
1
수정 버튼 눌렀을 때 이전 이미지 경로
0
437
1
이미지 수정이 안되고 이전 이미지 경로가 안떠요 ㅜㅜ
0
562
1
upload에서 제출 시 오류
0
614
2
여기 학습에 필요한 css 이거 어디에 있나요?
1
616
1

