• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

프론트로 이미지가 넘어오지가 않습니다

21.10.22 14:18 작성 조회수 104

0

안녕하세요 제로초님

5-4강좌를 다 듣고 진행중에 있는데 이미지가 업로드 되지가 않습니다 ㅜ

무슨 다른 에러는 하나도 뜨는게 없는데

네트워크 탭에 보면 Images가 비어있습니다.

router.post('/images', isLoggedIn, upload.array('image'), (req, res) => {
  console.log(req.files)
  return res.json(req.files.map(v => v.filename))
})

router.post('/', isLoggedIn, async (req, res, next) => {
  try {
    const hashtags = req.body.content.match(/#[^\s#]+/g)
    const newPost = await db.Post.create({
      content: req.body.content,
      UserId: req.user.id
    })
    if (hashtags) {
      const result = await Promise.all(hashtags.map(tag => db.Hashtag.findOrCreate({
        where: { name: tag.slice(1).toLowerCase() }
      })))
      await newPost.addHashtags(result.map(r => r[0]))
    }
    if (req.body.image) {
      if (Array.isArray(req.body.image)) {
        await Promise.all(req.body.image.map((image) => {
          return db.Image.create({ src: image, PostId: newPost.id })
        }))
      } else {
        await db.Image.create({ src: req.body.image, PostId: newPost.id})
      }
    }
    const fullPost = await db.Post.findOne({
      where: { id: newPost.id },
      include: [{
        model: db.User,
        attributes: ['id', 'nickname']
      }, {
        model: db.Image
      }]
    })
    return res.json(fullPost)
  } catch (err) {
    console.error(err)
    next(err)
  }
})

그런데 라우터 보시면 model : db.Image를 제대로 넣어놨는데 왜 안돼는지 모르겠습니다

아예 이미지를 서버로 전송 안해주나 생각해서 프론트도 봤는데 제로초님과 다른 코드는 발견하지 못했습니다 ㅜㅜ

무엇이 문제인지 피드백 받을 수 있을까요??

 

front/store/posts.js 의 액션

uploadImages({commit}, payload) {
    this.$axios.post('http://localhost:3085/post/images', payload, {
      withCredentials: true
    })
    .then((res) => {
      commit('concatImagePaths', res.data)
    })
    .catch((err) => {
      console.error(err)
  })

front/store/posts.js 의 뮤테이션

concatImagePaths(state, payload) {
    state.imagePath = state.imagePath.concat(payload)
},

front/components/postcard

<template>
<div>
  <v-card style="margin-bottom: 20px">
    <post-images :images="post.Images || []" />

PostImages 잘연결 해놨습니다

 

무엇이 문제일까요 ㅜ

답변 1

답변을 작성해보세요.

0

항상 코드만 보지 마시고 실제 디비를 봐보세요. 실제 디비에 이미지 데이터가 제대로 저장되어 있나요?

문종현님의 프로필

문종현

질문자

2021.10.22

예 알겠습니다

방금 워크브렌치 확인해봤는데 없네요 비어있습니다 ㅜ 왜그런걸까요!!ㅜ

데이터를 넣는 쪽에서부터 잘못된거겠죠

문종현님의 프로필

문종현

질문자

2021.10.22

예 그래서 한번 찾아보고있긴한데

back/models/image.js

module.exports = (sequelize, DataTypes) => {
  const Image = sequelize.define('Image', {
    src: {
      type: DataTypes.STRING(200),
      allowNull: false
    }
  }, {
    charset: 'utf8',
    collate: 'utf8_general_ci'
  })
  Image.associate = (db) => {
    db.Image.belongsTo(db.Post)
  }
  return Image;
}

 

back/models/post.js

module.exports = (sequelize, DataTypes) => {
  const Post = sequelize.define('Post', {
    content: {
      type: DataTypes.TEXT,
      allowNull: false
    }
  }, {
    charset: 'utf8mb4',
    collate: 'utf8mb4_general_ci'
  })
  Post.associate = (db) => {
    db.Post.belongsTo(db.User) // UserId
    db.Post.hasMany(db.Comment)
    db.Post.hasMany(db.Image)
    db.Post.belongsToMany(db.Hashtag, { through : 'PostHashtag' })
  }
  return Post;
}

보면 잘 설정하고 관계도 잘 해놓은거 같은데 ㅜ 

그리고 라우트 쪽에도

routes/post.js

router.post('/images', isLoggedIn, upload.array('image'), (req, res) => {
  console.log(req.files)
  return res.json(req.files.map(v => v.filename))
})

router.post('/', isLoggedIn, async (req, res, next) => {
  try {
    const hashtags = req.body.content.match(/#[^\s#]+/g)
    const newPost = await db.Post.create({
      content: req.body.content,
      UserId: req.user.id
    })
    if (hashtags) {
      const result = await Promise.all(hashtags.map(tag => db.Hashtag.findOrCreate({
        where: { name: tag.slice(1).toLowerCase() }
      })))
      await newPost.addHashtags(result.map(r => r[0]))
    }
    if (req.body.image) {
      if (Array.isArray(req.body.image)) {
        await Promise.all(req.body.image.map((image) => {
          return db.Image.create({ src: image, PostId: newPost.id })
        }))
      } else {
        await db.Image.create({ src: req.body.image, PostId: newPost.id})
      }
    }
    const fullPost = await db.Post.findOne({
      where: { id: newPost.id },
      include: [{
        model: db.User,
        attributes: ['id', 'nickname']
      }, {
        model: db.Image
      }]
    })
    return res.json(fullPost)
  } catch (err) {
    console.error(err)
    next(err)
  }
})

이거 보시면 model: db.Image 설정도 잘 해놨는데 제로초님은 무엇이 문제인지 확인 가능할까요??

 

 

문종현님의 프로필

문종현

질문자

2021.10.22

아 제로초님!! 해결했습니다 store부분에서 변수를 잘못 설정하여 안보내진거였습니다!!ㅜㅜ