• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

에러를 해결 못하겠습니다

22.03.26 18:17 작성 조회수 150

0

 

댓글 작성 후 submit을 누르면 이런 에러가 뜨는데 이유를 모르겠습니다. 

댓글 목록도 가져오지 못하는 것 같습니다 .ㅠㅠ 이유를 알 수 있을까요? ㅠㅠ

 

 

routes/comment.js

const express = require('express');
const router = express.Router();
const { Comment } = require("../models/Comment");

//=================================
//           Comment
//=================================

router.post('/saveComment',(req,res)=>{

    const comment = new Comment(req.body)

    comment.save((err,comment)=>{
        if(err) return res.json({success: false, err})
       
        Comment.find({'_id':comment._id})
        .populate('writer')
        .exec((err,result)=>{
            if(err) return res.json({success: false, err})
            res.status(200).json({success: true,result})
        })

    })
})

router.post('/getComments',(req,res)=>{

    Comment.find({"postId":req.body.videoid})
    .populate('writer')
    .exec((err,comments)=>{
        if(err) return res.status(400).send(err)
        res.status(200).json({success:true,comments})
    })
})



module.exports = router;

comment.js

import React, { useState } from 'react'
import axios from 'axios'
import {useSelector} from 'react-redux';
import SingleComment from './Singlecomment'


function Comment(props) {


  const videoId = props.postId
  const user=useSelector(state=>state.user); //redux/state/user 경로
  const [commentValue,setcommentValue]=useState("")
  const handleClick=(event)=>{

    setcommentValue(event.currentTarget.value)

  }

  const onSubmit=(event)=>{
    event.preventDefault();

    const variable={
      content:commentValue,
      writer:user.userData._id,
      postId:videoId
    }
    axios.post('/api/comment/saveComment',variable)
    .then(response=>{
      if(response.data.success){
        console.log(response.data.result)
        setcommentValue("")
        props.refreshFunction(response.data.result)
      }else{
        alert('코멘트를 저장하지 못했습니다.')
      }
    })

  }
  return (
    <div>
        <br />
        <p> Replies </p>
        <hr />
        {console.log(props.commentLists)}
        {props.commentLists && props.commentLists.map((comment, index) => (
          (!comment.responseTo &&
          <SingleComment refreshFunction={props.refreshFunction} comment={comment} postId={videoId} />
          )
        ))}

        <form style={{display:'flex'}} onSubmit={onSubmit}>
          <textarea
            style={{width: '100%' , borderRadius: '5px'}}
            onChange={handleClick}
            value={commentValue}
            placeholder="코멘트를 작성해주세요"
            />
            <br />
            <button style={{width: '20%', height : '52px'}} onClick={onSubmit}>Submit</button>
        </form>
    </div>
  )
}

export default Comment

VideoDetailPage.js

import React, { useEffect,useState } from 'react'
import {Row,Col,List,Avatar} from 'antd'
import { FaLaughSquint } from 'react-icons/fa'
import Axios from 'axios'
//import { post } from '../../../../../server/routes/video'
//import { response } from 'express'
import SideVideo from './Sections/SideVideo'
import Subscribe from './Sections/Subscribe'
import Comment from './Sections/Comment'

function VideoDetailPage(props) {


    //const [Comments,setComment]=useState(initialState)

    const videoId=props.match.params.videoId
    const variable={videoId: videoId}

    const [VideoDetail,setVideoDetail]=useState([])
    const [Comments,setComments]=useState([])

    useEffect(()=>{
        Axios.post('/api/video/getVideoDetail',variable)
        .then(response=>{
            if(response.data.success){
                setVideoDetail(response.data.videoDetail)
            }else{
                alert('비디오 정보 가져오기 실패')
            }
        })

        Axios.post('/api/comment/getComments', variable)
        .then(response=>{
            if(response.data.success){
                setComments(response.data.Comments)
            }else{
                alert('코멘트 정보 가져오기 실패')
            }
        })
    }, [])

    const refreshFunction=(newComment)=>{
        setComments(Comments.concat(newComment))
    }

    if(VideoDetail.writer){

        const subscribeButton = VideoDetail.writer._id!==localStorage.getItem('userId') &&  <Subscribe userTo={VideoDetail.writer._id} userFrom={localStorage.getItem('userId')}/>

        return (
            <Row gutter={[16,16]}>
                <Col lg={18} xs={24}>
       
                <div style={{width:'100%',padding:'3rem 4rem'}}>
                    <video style={{width:'100%'}} src={`http://localhost:5000/${VideoDetail.filePath}`} controls/>
       
                    <List.Item
                        actions={[subscribeButton]}
                    >
                        <List.Item.Meta
                            avatar={<Avatar src={VideoDetail.writer.image}/>}
                            title={VideoDetail.writer.name}
                            description={VideoDetail.description}
                        />
                    </List.Item>

                    <Comment refreshFunction={refreshFunction} commentLists={Comments} postId={videoId}/>
       
       
                </div>
       
                </Col>
                <Col lg={6} sx={24}>
                    <SideVideo/>
                </Col>
            </Row>
            //</div>
          )
        }else{
            return(
        <div>...loading</div>
            )
    }
}

export default VideoDetailPage

답변 1

답변을 작성해보세요.

0

안녕하세요   우선 Comments.concat() 하실 때  Comments에 올바른 형식의 데이터가 안들어 있을 것 같습니다.  console.log로 Comments State를 먼저 확인해주세요 ~ 감사합니다.

정말 감사합니다! 에러 해결했어요😀!