ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Youtube 만들기 - 6) 랜딩페이지에 비디오들 나타내기
    NODE.JS 2021. 5. 14. 18:13

     

    랜딩페이지에 업로드한 비디오들이 나오도록 해보자. 

    순서

     

    제일먼저 랜딩페이지를 설정해보자. 

    src>components>views>landingPage>LandingPage.js로 가자. 

    디자인을 위해서는 antd를 사용한다. 

     

    import React ,{useEffect,useState} from 'react'
    
    function LandingPage() {
    
    
        return (
    
            <div style={{ width:'85%', margin:'3rem auto'}}>
                <Title level={2}>Recommended</Title>
                <hr/>
                {/* Row하나당 Column의 갯수 정한다. 총 24사이즈로 화면 사이즈가 lg라면 화면에 4개가 보이고, md = 3개, xs = 1개가 보인다.   */}
                <Row gutter = {[32, 16]}>
                <Col lg = {6} md={8} xs={24}>
                    {/* 하나의 동영상에 해당하는 페이지로 이동 */}
                <a href={`/video/post/${video._id}`}>
                    <div style={{ position:'relative'}}>
                        <a href={`/video/${video._id}`}></a>
                        <img style = {{width:'100%'}} src={`http://localhost:5000/${video.thumbnail}`} alt=""/>
                        <div className="duration">
                            <span>{minutes}:{seconds}</span>
    
                        </div>
                    </div>
                </a>
                <br/>
                <Meta
                    avatar={
                        // Avatar는 유저 이미지 
                        <Avatar src={video.writer.image}/>
                    }
                    title = {video.title}
                    description=""
                
                />
                <span>{video.writer.name}</span><br/>
                <span style={{marginLeft:'3rem'}}>{video.views} views</span> - <span>{moment(video.createdAt).format("MMM Do YY")}</span>
    
            </Col>
    
                    
    
                </Row>
            </div>
        )
    }
    
    export default LandingPage
    

     

     

    비디오가 1개가 이니라 여러개이므로 계속 적용하기 위해서 renderCards함수를 따로 빼준다. 

            const renderCards = Video.map((video,index)=>{//비디오를 맵으로 묵는다.
                var minutes = Math.floor(video.duration/60);
                var seconds = Math.floor((video.duration - minutes*60));
                
                return <Col lg = {6} md={8} xs={24}>
                    {/* 하나의 동영상에 해당하는 페이지로 이동하기 위해서 비디오 아이디를 이용해 링크를 건다. */}
                <a href={`/video/post/${video._id}`}>
                    <div style={{ position:'relative'}}>
                        <a href={`/video/${video._id}`}></a>
                        <img style = {{width:'100%'}} src={`http://localhost:5000/${video.thumbnail}`} alt=""/>
                        <div className="duration">
                            <span>{minutes}:{seconds}</span>
    
                        </div>
                    </div>
                </a>
                <br/>
                <Meta
                    avatar={
                        // Avatar는 유저 이미지 
                        <Avatar src={video.writer.image}/>
                    }
                    title = {video.title}
                    description=""
                
                />
                <span>{video.writer.name}</span><br/>
                <span style={{marginLeft:'3rem'}}>{video.views} views</span> - <span>{moment(video.createdAt).format("MMM Do YY")}</span>//뷰 수와 업로드한 날짜 표시
    
            </Col>
            })
    
    
        return (
    
            <div style={{ width:'85%', margin:'3rem auto'}}>
                <Title level={2}>Recommended</Title>
                <hr/>
                {/* Row하나당 Column의 갯수 정한다.  */}
                <Row gutter = {[32, 16]}>
    
                    {renderCards}
                    
    
                </Row>
            </div>
        )
    }

     

     

    mongodb에서 비디오 정보를 가져오기 위해서 useEffect를 사용한다. 

    (리액트 훅)

    import React ,{useEffect,useState} from 'react'
    import { FaCode } from "react-icons/fa";
    import {Card, Icon, Avatar, Col, Typography, Row} from 'antd';
    
    import Axios from 'axios';
    
    const {Title} = Typography
    const {Meta} = Card;
    
    function LandingPage() {
        const [Video, setVideo] = useState([])//비디오가 여러개라서 배열에 담는다.
            
        useEffect(() => {
            Axios.get('/api/video/getVideos')
            .then(response =>{
                if(response.data.success){
                    setVideo(response.data.videos)//가져온 비디오들을 담는다.
    
                }
                else{ 
                    alert('비디오 가져오기를 실패 했습니다.')
                }
            })
    
        }, [])//input 부분이 없으면 계속 실행 있으면 한번만 실행

     

     

    axios를 했으니 비디오 route를 생성해준다. 

    video.js

    router.post('/getVideos', (req, res)=>{
        //비디오를 DB에서 가져와서 클라이언트에 보낸다.
        Video.find() //모든 비디오를 가져온다
        .populate('writer')//populate를 해줘야 user관련 데이터를 가져올수 있다. 안하면 id만 가져온다. 
        .exec((err, video)=>{
            if(err)return res.status(400).send(err);
            res.status(200).json({success:true,videos})
        })
    })
    
    

     

     

     

    index.css에 가서 duration 디자인을 준다. 

    .duration {
      bottom:0;
      right:0;
      position: absolute;
      margin: 4px;
      color: #fff;
      background-color: rgba(17, 17, 17, 0.8);
      opacity: 0.8;
      padding: 2px 4px;
      border-radius: 2px;
      letter-spacing: 0.5px;
      font-size: 12px;
      font-weight: 500;
      line-height: 12px;
    }
    

     

     

     

     

     

     

    완성된 화면

     

     

     

     

     

     

     

     

     

     

Designed by Tistory.