Dance&Dancer_Match_6) 2020_06_12

오범준·2020년 6월 17일
0

To Do

1. Using Ejs

I am using efs, to show profile

( server code ) mypage.js


// 2. Dancer
router.get('/api/users/mypageDancer', function( req , res){

    var x_auth = req.cookies.x_auth

    console.log('x_auth',x_auth)

    connection.db.collection("dancers", function(err, collection){
        collection.find({token:x_auth}).toArray(function(err, data){
            //data는 내가 찾은 token에 해당하는 데이터이다
            // 즉, 내가 찾는 댄서에 대한 정보가 data로 들어오는데
            // array 형식으로 들어오기 때문에, data[0]이라고 작성하는 것이다 
        console.log(data[0])
        res.render('mypageDancer',data[0])
        })   
    });
});

router.post('/profile/update_dancer',function(req,res)
{
    // cookie 가져오기
    var x_auth = req.cookies.x_auth
    //업데이트할 변수명
    var name = req.body.name
    //업데이트할 값
    var value = req.body.value
    console.log('name')
    //x-auth token으로 찾아서 update
    connection.db.collection("dancers", function(err, collection){

        collection.updateOne({'token':x_auth},{$set:{[name]:value}}, 
        //변수명을 mongoose column 명으로 사용하고 싶을 때 [name]->e_name
        {upsert:true });
        if(err)
        {
            console.log(err)
            res.status(404)
        }
        var result='ok'
        var respondData={'result':result}
        res.json(respondData)
    })
})

Above is the front code that is shown to the client
The word "Image, username, ... etc" are the variables in DB related with Dancer

mypageDancer.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href = "../../cssjs/mypage.css" rel = "stylesheet"/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- add to document <head> -->
  <link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet">
  <link href="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css" rel="stylesheet">

  <!-- add before </body> -->
  <script src="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.js"></script>
  <!-- add before </body> -->
  <script src="https://unpkg.com/filepond/dist/filepond.js"></script>

    <title>myprofileDancer</title>
</head>
<body>
      <div class="container">
            <div id="logo"><h1 class="logo"><a href="/main"><i class="fa fa-home" aria-hidden="true"></i></a></h1>
      </div>
            <div class="leftbox">
              <nav>
                <a id="profile" class="active"><i class="fa fa-user"></i></a>
                <a id="privacy"><i class="fa fa-tasks"></i></a>
                <a id="payment"><i class="fa fa-credit-card"></i></a>
                <a id="subscription"><i class="fa fa-tv"></i></a>
                <a id="settings"><i class="fa fa-cog"></i></a>
              </nav>
            </div>
            <div class="rightbox">
              <div class="profile">
                <div class="user-img">
                  <% if(Image) { %>
                    <img id="display-image" src=<%= Image %>>
                    <% }
                    else{ %>
                      <img id="display-image" src="https://source.unsplash.com/random/1">
                     <% } %>
                    <div class="container-btn">
                    <button id='upload-btn'>
                    <label for="upload">
                      upload
                     </label>
                    </button>
                    <button id='clear-btn' class="btn-deactive">
                        Clear
                    </button>
                    <form action="/api/users/mypageDancer" method="POST" enctype="multipart/form-data">
                      <input type="file" name="image" id="upload" onChange="handleImageUpload()" class="btn-deactive"/>
                      <input type="submit" id="submit-btn" class='btn-deactive' />
                    </form>
                    </div>
                </div>
                <h2>User Name</h2>
                <p><input type="text" name="username" value="<%= username %>"> <button class="btn">update</button></p>
                <h2>Email</h2>
                <p><input type="text" name="age" value="<%= email %>"> <button class="btn">update</button></p>
                <h2>Contact</h2>
                <p><input type="text" name="Contact" value="<%= Contact %>"> <button class="btn">update</button></p>
              </div>
              <div class="privacy noshow">
                <h1>Other Info</h1>
                <h2>English Name</h2>
                <p><input type="text" name="e_name" value="<%= e_name %>"> <button class="btn">update</button></p>
                <h2>Korean Name</h2>
                <p><input type="text" name="k_name" value="<%= k_name %>"> <button class="btn">update</button></p>
                <h2>Age</h2>
                <p>
                    <select name='age' id='age'>
                        <option value="0s">
                          1 ~ 10
                        </option>
                        <option value="10s">
                          10 ~ 19
                        </option>
                        <option value="20s">
                          20 ~ 29
                        </option>
                        <option value="30s">
                          30 ~ 39
                        </option>
                        <option value="40s">
                          40 ~ 49
                        </option>
                        <option value="50s">
                          50 ~ 59
                        </option>
                        <option value="60s">
                          60 ~ 69
                        </option>
                        <option value="70over">
                          70 ~
                        </option>
                        </select>
                        <button class="btn">update</button>
                </p>
                <h2>Gender</h2>
                <p>                
                    <select id="gender" name="gender">
                        <option value="M">Male</option>
                        <option value="F">Female</option>
                        <option value="Etc">Etc</option>
                    </select> <button class="btn">update</button></p>
                <h2>Place</h2>
              
                <p>
                  <select id="place" name="place">
                  <option value="Jongno-gu">
                    Jongno-gu 종로구</option>
                  <option value="Jung-gu">Jung-gu 중구</option>
                  <option value="Yongsan-gu">
                    Yongsan-gu 용산구</option>
                  <option value="Seongdong-gu">
                    Seongdong-gu 성동구</option>
                  <option value="Gwangjin-gu">
                    Gwangjin-gu 광진구</option>
                  <option value="Dongdaemun-gu">
                    Dongdaemun-gu 동대문구</option>
                  <option value="Jungnang-gu">Jungnang-gu 중랑구</option>
                  <option value="Seongbuk-gu">
                    Seongbuk-gu 성북구</option>
                  <option value="Gangbuk-gu">Gangbuk-gu 강북구</option>
                  <option value="Dobong-gu">Dobong-gu 도봉구</option>
                  <option value="Nowon-gu">
                    Nowon-gu 노원구</option>
                  <option value="Eunpyeong-gu">
                    Eunpyeong-gu 은평구</option>
                  <option value="Seodaemun-gu">Seodaemun-gu 서대문구</option>
                  <option value="Mapo-gu">Mapo-gu 마포구</option>
                  <option value="Yangcheon-gu">Yangcheon-gu 양천구</option>
                  <option value="Gangseo-gu">
                    Gangseo-gu 강서구</option>
                  <option value="Guro-gu">
                    Guro-gu 구로구</option>
                  <option value="Geumcheon-gu">
                    Geumcheon-gu 금천구</option>
                  <option value="Yeongdeungpo-gu">
                    Yeongdeungpo-gu 영등포구</option>
                  <option value="Dongjak-gu">
                    Dongjak-gu 동작구</option>
                  <option value="Gwanak-gu">
                    Gwanak-gu 관악구</option>
                  <option value="Seocho-gu">
                    Seocho-gu 서초구</option>
                  <option value="Gangnam-gu">
                    Gangnam-gu 강남구</option>
                  <option value="Songpa-gu">
                    Songpa-gu 송파구</option>
                  <option value="Gangdong-gu">Gangdong-gu 강동구</option>
                </select> <button class="btn">update</button></p>
                <h2>Genre</h2>
                <p>
                  <select id="genre1" class="genre" name="genre">
                      <option value="K_Pop">K_Pop</option>
                      <option value="Hip_Hop">Hip_Hop</option>
                      <option value="Girlish">Girlish</option>
                      <option value="Girls_HipHop">Girls_HipHop</option>
                      <option value="Girls_HipHop">Girls_HipHop</option>
                      <option value="Poppin">Poppin</option>
                      <option value="Locking">Locking</option>
                      <option value="House">House</option>
                      <option value="Breaking">Breaking</option>
                      <option value="Ballet">Ballet</option>
                      <option value="Korea_Dance">Korea_Dance(한국무용)</option>
                      <option value="Modern_Dance">Modern_Dance(현대무용)</option>
                      <option value="Choreography">Choreography</option>
                      <option value="Salsa">Salsa</option>
                      <option value="Dance_Sports">Dance_Sports</option>
                      <option value="Etc">Etc( 그외 )</option>
                </select>
                <select id="genre2" class="genre" name="genre">
                    <option value="K_Pop">K_Pop</option>
                    <option value="Hip_Hop">Hip_Hop</option>
                    <option value="Girlish">Girlish</option>
                    <option value="Girls_HipHop">Girls_HipHop</option>
                    <option value="Girls_HipHop">Girls_HipHop</option>
                    <option value="Poppin">Poppin</option>
                    <option value="Locking">Locking</option>
                    <option value="House">House</option>
                    <option value="Breaking">Breaking</option>
                    <option value="Ballet">Ballet</option>
                    <option value="Korea_Dance">Korea_Dance(한국무용)</option>
                    <option value="Modern_Dance">Modern_Dance(현대무용)</option>
                    <option value="Choreography">Choreography</option>
                    <option value="Salsa">Salsa</option>
                    <option value="Dance_Sports">Dance_Sports</option>
                    <option value="Etc">Etc( 그외 )</option>
              </select>
              <select id="genre3" class="genre" name="genre">
                  <option value="K_Pop">K_Pop</option>
                  <option value="Hip_Hop">Hip_Hop</option>
                  <option value="Girlish">Girlish</option>
                  <option value="Girls_HipHop">Girls_HipHop</option>
                  <option value="Girls_HipHop">Girls_HipHop</option>
                  <option value="Poppin">Poppin</option>
                  <option value="Locking">Locking</option>
                  <option value="House">House</option>
                  <option value="Breaking">Breaking</option>
                  <option value="Ballet">Ballet</option>
                  <option value="Korea_Dance">Korea_Dance(한국무용)</option>
                  <option value="Modern_Dance">Modern_Dance(현대무용)</option>
                  <option value="Choreography">Choreography</option>
                  <option value="Salsa">Salsa</option>
                  <option value="Dance_Sports">Dance_Sports</option>
                  <option value="Etc">Etc( 그외 )</option>
            </select>
                <button class="btn">update</button></p>
              </div>
              
              <div class="payment noshow">
                <h1>Payment Info</h1>
                <h2>Payment Method</h2>
                <p>Mastercard •••• •••• •••• 0000 <button class="btn">update</button></p>
                <h2>Billing Address</h2>
                <p>1234 Example Ave | Seattle, WA <button class="btn">change</button></p>
                <h2>Zipcode</h2>
                <p>999000</p>
                <h2>Billing History</h2>
                <p>2018<button class="btn">view</button></p>
                <h2>Redeem Gift Subscription </h2>
                <p><input type="text" placeholder="Enter Gift Code" /> <button class="btn">Redeem</button></p>
              </div>
              <div class="subscription noshow">
                <h1>Your Subscription</h1>
                <h2>Payment Date</h2>
                <p>05-15-2018 <button class="btn">pay now</button></p>
                <h2>Your Next Charge</h2>
                <p>$8.48<span> includes tax</span></p>
                <h2>Hulu Base Plan</h2>
                <p>Limited Commercials <button class="btn">change plan</button></p>
                <h2>Add-ons</h2>
                <p>None <button class="btn">manage</button></p>
                <h2>Monthly Recurring Total </h2>
                <p>$7.99/month</p>
              </div>
           <div class="settings noshow">
                <h1>Account Settings</h1>
                <h2>Sync Watchlist to My Stuff<button class="btn">sync</button></h2>
                <p></p>
                <h2>Hold Your Subscription<button class="btn">hold</button></h2>
                <p></p>
                <h2>Cancel Your Subscription <button class="btn">cancel</button></h2>
                <p></p>
                <h2>Your Devices <button class="btn">Manage Devices</button></h2>
                <p></p>
                <h2>Referrals <button class="btn">get $10</button></h2>
             <p></p>
              </div>
            </div>
          </div>
          <script>
            
                  var gender = "<%= Gender %>";
                  document.body.querySelector('#gender').value=gender;
                  var genres_gui = document.body.querySelectorAll('.genre');
                  var genres_data = <%-JSON.stringify(genre)%>;
          </script>
          <script src="../../cssjs/mypage/mypage.js"></script> 
</body>
</html>

  

But I am showing Below Errors

It is because, the "Image" Variable is not saved in DB

Dancer.js ( schema )

During Regsitration process, dancer is not requireed to upload their own images, that is why, image data is not saved in DB

but in order to remove that kind of error,
I have to save variable anyway

Solution : make default of Image

From the very beginning, I was thinking of storing entire image into DB.
But, instead, It would be better if I save the path instead

So, I used "AWS S3 Storebase" as an alternative

2. Using S3 server

Pb 1.AccessDenied: Access Denied

Request for uploading image
Error during uploading image

< router/file_upload.js >

const express = require('express');
const router = express.Router();
const path = require('path');
const { User } = require('../models/User')
const upload = require('../services/file_upload.js');
const { resolve } = require('url');

// 'image'는 key의 역할을 한다
// under this key, we will send our image
const singleUpload = upload.single('image');

router.post('/api/users/image-upload', function( req, res){

    singleUpload( req, res, function( err ){   

        console.log("Request for uploading image");
        
        if(err){
            console.log("Error during uploading image");
            console.log(err)
        }

        console.log("hello");
        
        
        // location에는 url of our image 이 들어있을 것이다 
        return res.json({ 'imageUrl' : req.file.location})

    });   
})

module.exports = router;

< services/ file_upload.js>

// service 전용 js
const aws = require('aws-sdk');
const express = require('express');
const multer = require('multer');
const multerS3 = require('multer-s3');
const config = require('../config/dev');

aws.config.update({
  secretAccessKey : config.AWS_SECRET_ACCESS ,
  accessKeyId : config.AWS_ACCESS_KEY,
  region : "ap-northeast-2"
})
 
const app = express();
const s3 = new aws.S3({ });
 
// upload object를 만들고 있다
// storage를 provide 하고 있으며, storage의 이름은 multerS3 이다 
var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'danceprojectmb',
    // 내가 image를 보내면, 그것을 imageurl 형태로 저장한다 . 그리고 그 image 에 대해서, public access를 줄 때 아래와 같은 코드를 작성한다 
    acl : 'public-read',
    metadata: function (req, file, cb) {
        // fieldName은 addional info를 주는 것이다
      cb(null, {fieldName: "TESTING_META_DATA"});
    },
    // 우리가 AWS에 image등을 save 하기 전에 key와 함께 저장을 할 것이다 . 이 경우 key는 timestamp로 구성될 것이다. 다시 말해서 이 key에 대항하는 것은 우리가 save 한 file일 것이다 
    key: function (req, file, cb) {
      cb(null, Date.now().toString())
    }
  })
})


module.exports = upload;

Solution

You should allow public access to your s3 repository

profile
Dream of being "물빵개" ( Go abroad for Dance and Programming)

0개의 댓글