-
카테고리
-
세부 분야
풀스택
-
해결 여부
미해결
해시태그와 이미지 업로드가 안됩니다.
22.03.17 11:37 작성 조회수 125
0
해시태그를 달고 이미지 첨부해서 올려도 게시글과 사진이 서버로 넘어가지 않는거 같습니다.
Request 요청은 가는데 그 이후로 처리가 안되네요. MySQL Workbench에서 새로고침눌러봐도 게시글 해시태그 이미지 모두 안올라 가집니다..
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { Post, Image, Comment, User, Hashtag } = require('../models');
const { isLoggedIn } = require('./middlewares');
const router = express.Router();
try {
fs.accessSync('uploads');
} catch (error) {
console.log('uploads 폴더가 없으므로 생성합니다.');
fs.mkdirSync('uploads');
}
const upload = multer({
storage: multer.diskStorage({
destination(req, file, done) {
done(null, 'uploads');
},
filename(req, file, done) {
const ext = path.extname(file.originalname); // 확장자 추출(png)
const basename = path.basename(file.originalname, ext); // 레니
done(null, basename + '_' + new Date().getTime() + ext); // 레니15335436332.png
},
}),
limits: { fileSize: 20 * 1024 * 1024 }, // 20MB
});
router.post('/', isLoggedIn, upload.none(), async (req, res, next) => {
try {
const hashtags = req.body.content.match(/#[^\s#]+/g);
const post = await Post.create({
content: req.body.content,
UserId: req.user.id,
});
if (hashtags) {
const result = await Promise.all(hashtags.map((tag) => Hashtag.findOrCreate({
where: {name: tag.slice(1).toLowerCase() },
}))); // [[노드, true], [리액트, true]]
await post.addHashtags(result.map((v) => v[0]));
}
if (req.body.image) {
if (Array.isArray(req.body.image)) { // 이미지를 여러개 올리면 배열로 올라감
const images = await Promise.all(req.body.image.map((image) => Image.create({ src: image }))); // map을 해서 시퀄라이즈 create 만들어주세요.
await post.addImages(images);
} else { // 이미지를 하나만 올리면 image: 레니.png
const image = await Image.create({ src: req.body.image });
await post.addImages(image);
}
}
const fullPost = await Post.findOne({
where: { id: post.id },
include: [{
model: Image,
}, {
model: Comment,
include: [{
model: User, // 댓글 작성자
attributes: ['id', 'nickname'],
}],
}, {
model: User, // 게시글 작성자
attributes: ['id', 'nickname'],
}, {
model: User, // 좋아요 누른 사람
as: 'Likers',
attributes: ['id'],
}]
})
res.status(201).json(fullPost);
} catch(error) {
console.error(error);
next(error);
}
});
router.post('/images', isLoggedIn, upload.array('image'), async (req, res, next) => { // POST /post/images
console.log(req.files);
res.json(files.map((v) => v.filename));
});
router.post('/:postId/comment', isLoggedIn, async (req, res, next) => { // POST / post/1/comment
try {
const post = await Post.findOne({
where: { id: req.params.postId }
});
if (!post) {
return res.status(403).send('존재하지 않는 게시글입니다.');
}
const comment = await Comment.create({
content: req.body.content,
PostId: parseInt(req.params.postId, 10), // reducer > post.js > ADD_COMMENT_SUCCESS -> action.data.PostId 대소문자 일치시켜주어야 한다!
UserId: req.user.id,
})
// const fullComment = await Comment.findOne({
// where: { id: comment.id },
// include: [{
// model: User,
// attributes: ['id', 'nickname'],
// }],
// })
res.status(201).json(comment);
} catch(error) {
console.error(error);
next(error);
}
});
router.patch('/:postId/like', isLoggedIn, async (req, res, next) => { // PATCH /post/1/like
try {
const post = await Post.findOne({ where: { id: req.params.postId }});
if (!post) {
return res.status(403).send('게시글이 존재하지 않습니다.');
}
await post.addLikers(req.user.id);
res.json({ PostId: post.id, UserId: req.user.id});
} catch (error) {
console.error(error);
next(error);
}
});
router.delete('/:postId/like', isLoggedIn, async (req, res, next) => { // DELETE /post/1/like
try {
const post = await Post.findOne({ where: { id: req.params.postId }});
if (!post) {
return res.status(403).send('게시글이 존재하지 않습니다.');
}
await post.removeLikers(req.user.id);
res.json({ PostId: post.id, UserId: req.user.id});
} catch (error) {
console.error(error);
next(error);
}
});
router.delete('/:postId', isLoggedIn, async (req, res) => { // DELETE /post/10
try {
await Post.destroy({
where: {
id: req.params.postId,
UserId: req.user.id,
},
});
res.status(200).json({ PostId: parseInt(req.params.postId, 10) });
} catch(error) {
console.error(error);
next(error);
}
});
module.exports = router;
답변을 작성해보세요.
답변 0