inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[리뉴얼] React로 NodeBird SNS 만들기

해시태그 등록하기

해시태그와 이미지 업로드가 안됩니다.

192

Trendy Tube

작성한 질문수 14

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;

 

 

 

 

 

 

nodejs express redux react Next.js

답변 0

넥스트 버젼 질문

0

91

2

로그인시 401 Unauthorized 오류가 뜹니다

0

104

1

무한 스크롤 중 스크롤 튐 현상

0

199

1

특정 페이지 접근을 막고 싶을 때

0

117

2

createGlobalStyle의 위치와 영향범위

0

104

2

인라인 스타일 리렌더링 관련

0

99

2

vsc 에서 npm init 설치시 오류

0

159

2

nextjs 15버전 사용 가능할까요?

0

166

1

화면 새로고침 문의

0

129

1

RTK에서 draft, state 차이가 있나요?

0

164

2

Next 14 사용해도 될까요?

0

455

1

next, node 버전 / 폴더 구조 질문 드립니다.

0

360

1

url 오류 질문있습니다

0

218

1

ssh xxxxx로 우분투에 들어가려니까 port 22: Connection timed out

0

394

1

sudo certbot --nginx 에러

0

1298

2

Minified React error 콘솔에러 (hydrate)

0

483

1

카카오 공유했을 때 이전에 작성했던 글이 나오는 버그

0

257

1

프론트서버 배포 후 EADDRINUSE에러 발생

0

341

1

npm run build 에러

0

526

1

front 서버 npm run build 중에 발생한 에러들

0

399

1

서버 실행하고 브라우저로 들어갔을때 404에러

0

351

2

css 서버사이드 랜더링이 적용되지 않아서 문의 드립니다.

0

291

1

팔로워 3명씩 불러오고 데이터 합쳐주는걸로 바꾸고 서버요청을 무한으로하고있습니다.

0

253

2

해시태그 검색에서 throttle에 관해 질문있습니다.

0

207

1